C Union


Union in c language is a user defined datatype that is used to hold different type of elements.


Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.


Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union.

Syntax

union union_name   
{  
    data_type member1;  
    data_type member2;  
    .  
    .  
    data_type memeberN;  
};  

Example

#include <stdio.h>  
#include <string.h>  
union student    
{   int id;    
    char name[50];    
}s1;  //declaring s1 variable for union  
int main( )  
{  
   //store student information  
   s1.id=11211855;  
   //copying string into char array 
   strcpy(s1.name, "Sachin Yadav");
    
   //printing Student information  
   printf( "Student id : %d\n", s1.id);  
   printf( "Student name : %s\n", s1.name);  
   return 0;  
}
Output
Student id: 11211855
Student name: Sachin Yadav

Share this article on