Home >>C Tutorial >C Union

Union in C

Union in C

Union in C language is basically a special data type that are known to store different data types in the same memory location. It is similar to the structure in C language.

The memory can be occupied by only one member of the union at a particular time. In simple words, you can understand it as, in any situation the size of the union is equal to the size of its biggest element in terms of size.

Advantage of the union over structure in C

As the union is known to occupy the size of the largest element only hence, it occupies less memory.

Disdvantage of the union over structure in C

As the previously stored data is overwritten in the union because of which only the data that is entered in the last is stored in the union.

Process of defining union in C

In order to define the union in C language, union keyword is used.

Here is the syntax to define union in C language:

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

Union Example in C

#include <stdio.h>  
#include <string.h>  
union employee    
{   int Empid;    
    char name[50];    
}
emp;  //emp variable declare for union  
int main( )  
{  
   //Store emply id first  
   emp.Empid=100;  
   strcpy(emp.name, "Shipra"); 
   //print employee information   
   printf( "Emp 1 id = %d\n", emp.Empid);  
   printf( "Emp 1 name= %s\n", emp.name);  
   return 0;  
}  
Output :
Emp 1 id = 1885956179
Emp 1 name= Shipra

Note : You can see here, Empid display garbage value this is large memory size of name variable. So here it display name onlye actual value.


Popular Tutorials