C Unions

In C, unions are user-defined data types similar to structures with one key difference. Structures allocate space to accommodate all its members whereas union allocates space according to the size of the largest member. Unions are created using the union keyword.

Syntax

union tag {
    dataType var1;
    dataType var2;
    //more member definitions
}union_variable(s);

//or union without a tag
union {
    dataType var1;
    dataType var2;
    //more member definitions
}union_variable(s);

Size of Union

As said earlier, union allocates space according to the size of the largest member because all data members in a union share the common memory. We can check if this is true by using the sizeof operator. Note: The size allocated by the union/structure may be adjusted, example, 63 bytes adjusted to 64 bytes.

Code

#include<stdio.h>

union Girl
{
    char name[64];    //64 bytes
    int age;          //4 bytes - not considered
    float height;     //4 bytes - not considered
};  

struct Boy
{
    char name[64];    //64 bytes
    int age;          //4 bytes
    float height;     //4 bytes
};

int main(void)
{
    union Girl maya;
    struct Boy yamato;
	
    printf("maya (union): %d\n",sizeof(maya));
    printf("yamato (struct): %d\n",sizeof(yamato));
    
    return 0;
}

Output

maya (union): 64
yamato (struct): 72

In unions, if two or more members are initialized, then only the latest initialized data member will hold the data. The following code demonstrates an example using unions.

Code

#include<stdio.h>
#include<string.h> 

union Student{
    char name[50];
    int roll;
};
 
int main(void)
{
    union Student student1;
    union Student student2;
    
    strcpy(student1.name,"Charlie");    //holds garbage
    student1.roll = 1;
    
    student2.roll = 2;    //holds garbage
    strcpy(student2.name,"Olivia");
    
    //Accessing student1 details using Member selection via object name 
    printf("Student 1 Name: %s\n",student1.name);
    printf("Student 1 Roll No.: %d\n",student1.roll);
    
    //Creating a reference to student2
    union Student *ref_student2 = &student2;
    
    //Accessing student2 details using Member selection via pointers 
    printf("Student 2 Name: %s\n",ref_student2->name);
    printf("Student 2 Roll No.: %d\n",ref_student2->roll);
    
    return 0;
}

Output

Student 1 Name: garbage
Student 1 Roll No.: 1
Student 2 Name: Olivia
Student 2 Roll No.: 2020

Trending

C Programming

Remember to follow community guidelines and don't go off topic.