Union in c language


  • Union is a user defined data type which contains variables of different data types.
  • Or we can say that, union is collection of dissimilar type of elements or data.
  • The concept of union is taken from structure so the syntax of union is same as structure.
  • In structure each member get separate memory for storage while in union all the members share same storage location.
  • As all the members share same storage so we can work on only one member at a time.
  • The compiler allocates total memory equal to the member having largest size.

    Syntax:

    union
    name_of_union
    {
     member 1;
     member 2;
     . . . . .
     member n;
    };

Declaring Union Variable

  • We can declare variable of union in the same way we do for structure. For example if we want to declare variables for above union then it can be done in following way.
  • union student s1,s2;

Accessing Union Members

  • We can access a union member by using dot operator (.). Remember that, access only that variable whose value is currently stored. Consider below example.
  • s1.rollno = 20;
    s1.mark = 90.0;
    printf("%d",s1.rollno);

    The above code will give erroneous output. This is because we have most recently sored value in mark and we are accessing rollno. When value is assigned to a member then the value that was assigned to any other member before is lost.

    Initializing Union:

    union student s1 = {25}; //valid
    union student s1 = {80.5};  //will give undesired or erroneous output
    

    In above example the first statement is correct while second statement will give undesired output because we are initializing second member mark (float type) of union student.

    Example:

    #include<stdio.h>
    void main()
    {
    union student {
    int rollno;
    float mark;
    char gender;
     }s1; 
     s1.rollno=30;
    printf("Roll No:%d",s1.rollno);
    s1.mark=92.5;
    printf("nMark:%f",s1.mark);
    s1.gender='Male';
    printf("nGender:%c",s1.gender);
    }
    

    Output:

    Roll No=30
    Mark=92.5
    Gender=Male