C Unions

C Unions are nothing but, a collection of different data types that are grouped together. And these are like structures. While the only difference between unions and structures is allocating memory for their members. For defining a union we need union keyword. To access any member of a union, we use the member access operator (.).

Syntax
union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};

Unions in C

  • C Unions allocates only one common storage space for all its members.
  • All variables inside the unions known as members of the union.
  • the memory occupied by the union will be large enough to hold the largest member of the union.
  • In union, if we initializing multiple members then compiler gives an error.

Example

#include<stdio.h>       
#include<string.h>      
union student {            
char name[20];            
char subject[20];            
float percentage;       
};       
int main() {            
union student record1;          
union student record2;// assigning values to record1 union variable       
strcpy(record1.name, "Raju");       
strcpy(record1.subject, "Maths");       
record1.percentage = 86.50;       
printf("Union record1 values example\n");       
printf("Name:%s \n", record1.name);       
printf(" Subject:%s \n", record1.subject);       
printf(" Percentage : %f \n\n", record1.percentage);//assigning values to record2 union variable       
printf("Union record2 values example\n");       
strcpy(record2.name, "Mani");       
printf("Name:%s \n",record2.name);       
strcpy(record2.subject,"Physics");       
printf("Subject:%s \n",record2.subject);       
record2.percentage = 99.50;       
printf("Percentage : %f \n",record2.percentage);       
return 0;
}

Output
Union record1 values example
Name :
Subject :
Percentage : 86.500000;
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000

Example 2

#include<stdio.h>    
#include<string.h>  
union student  {            
char name[20];            
char subject[20];            
float percentage;  
}
record;   
int main() {            
strcpy(record.name, "Raju");            
strcpy(record.subject, "Maths");            
record.percentage = 86.50;            
printf("Name: %s \n", record.name);            
printf("Subject: %s\n",record.subject);            
printf("Percentage:%f \n",record.percentage);            
return 0; }

Output
Name :
Subject :
Percentage : 86.500000

Difference between unions and structures

Example

#include<stdio.h>
union unionJob
{
   //defining a union
   char name[32];
   float salary;
   int workerNo;
} uJob;
struct structJob
{
   char name[32];
   float salary;
   int workerNo;
} sJob;
int main()
{
   printf("size of union = %d bytes", sizeof(uJob));
   printf("\nsize of structure = %d bytes", sizeof(sJob));
   return 0;
}

Output
size of union = 32
size of structure = 40