Home >>C Tutorial >C Union
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.
As the union is known to occupy the size of the largest element only hence, it occupies less memory.
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.
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; };
#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; }
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.