Both structure and union are collection of different datatype. They are used to group number of variables of different type in a single unit.
Union declaration
Declaration of union must start with the keyword union followed by the union name and union's member variables are declared within braces.
Syntax for declaring union
union union-name { datatype var1; datatype var2; - - - - - - - - - - - - - - - - - - - - datatype varN; };
Accessing the union members
We have to create an object of union to access its members. Object is a variable of type union. Union members are accessed using the dot operator(.) between union's object and union's member name.
Syntax for creating object of union
union union-name obj;
Example for creating object & accessing union members
#include<stdio.h>
union Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void main()
{
union Employee E;
printf("\nEnter Employee Id : ");
scanf("%d",&E.Id);
printf("\nEnter Employee Name : ");
scanf("%s",&E.Name);
printf("\nEnter Employee Age : ");
scanf("%d",&E.Age);
printf("\nEnter Employee Salary : ");
scanf("%ld",&E.Salary);
printf("\n\nEmployee Id : %d",E.Id);
printf("\nEmployee Name : %s",E.Name);
printf("\nEmployee Age : %d",E.Age);
printf("\nEmployee Salary : %ld",E.Salary);
}
Output
In the above example, we can see that values of Id, Name and Age members of
union got corrupted because final value assigned to the variable has occupied the memory
location and this is the reason that the value of salary member is getting printed
very well. Now let's look into the same example once again where we will use one variable at a time which is the main purpose of having union:
#include<stdio.h>
union Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void main()
{
union Employee E;
printf("\nEnter Employee Id : ");
scanf("%d",&E.Id);
printf("Employee Id : %d",E.Id);
printf("\n\nEnter Employee Name : ");
scanf("%s",&E.Name);
printf("Employee Name : %s",E.Name);
printf("\n\nEnter Employee Age : ");
scanf("%d",&E.Age);
printf("Employee Age : %d",E.Age);
printf("\n\nEnter Employee Salary : ");
scanf("%ld",&E.Salary);
printf("Employee Salary : %ld",E.Salary);
}
Output
Here, all the members are getting printed very well because one member is being
used at a time.
No comments:
Post a Comment