C Language



Admission Enquiry Form

  

Union in C


What is Union in C?

Union is user defined data type like structure which can store different data types,but all members share the same memory location.We can declare a union with many data members, but only one data member can contain a value at a given time.

Syntax to declare Union

union unionName
{
dataType member1;
dataType member2;
dataType member3;
...
};



We can declare structure with keyword union.Here, member1,member2,member3 are the data member of a union.



Create variable of a union

union unionName
{
dataType member1;
dataType member2;
dataType member3;
...
}variable_name;

Another way of creating variable of union

union unionName
{
dataType member1;
dataType member2;
dataType member3;
...
};
void main()
{
union unionName variable_name;
}





Operators used to access the data members of a Union

. -This is dot or period operator used to access the data members of a union.
-> -This is arrow or indirection operator used to access the data members of a union using pointer.




Example:

#include<stdio.h>
union student
{
int rollno;
float fee;
char name[10];
}st;

void main()
{

 //union student st;
printf("Enter rollno");
scanf("%d",&st.rollno);
printf("Enter fee");
scanf("%f",&st.fee);
printf("Enter name");
scanf("%s",&st.name);

 printf("\nRollno is %d",st.rollno);
printf("\nFee is %f",st.fee);
printf("\nName is %s",st.name);
}


When the above code is executed, it will produce the following Output:

Enter rollno 10
Enter fee 5000
Enter name priya

Rollno is 2036953712
Fee is 75757889767977045000000000000000000.000000
Name is priya


Here, we can see the output.Values of rollno and fee members of union got corrupted because all the members are sharing the same memory location and the final value assigned to the name variable has occupied the memory location.So that the value of name data member is printed.

Now practice the same example one more time where we will print one variable at a time which is the main purpose of a union.



Example:

#include<stdio.h>
union student
{
int rollno;
float fee;
char name[10];
}st;

void main()
{
//union student st;
printf("Enter rollno ");
scanf("%d",&st.rollno);
printf("Rollno is %d",st.rollno);
printf("\n\nEnter fee ");
scanf("%f",&st.fee);
printf("Fee is %f",st.fee);
printf("\n\nEnter name ");
scanf("%s",&st.name);
printf("Name is %s",st.name);


Output:

Enter rollno 10
Rollno is 10

Enter fee 6000
Fee is 6000.000000

Enter name neha
Name is neha


Here, the values of all the data members are getting printed because one member is being used at a time.