A union is a memory location that is shared by several variables of different data types in C programming language.
Syntax
The syntax for union of structure is as follows −
union uniontag{ datatype member 1; datatype member 2; ---- ---- datatype member n; };
Example
The following example shows the usage of union of structure −
union sample{ int a; float b; char c; };
Declaration of union variable
Following is the declaration for union variable. It is of three types as follows −
Type 1
union sample{ int a; float b; char c; }s;
Type 2
union{ int a; float b; char c; }s;
Type 3
union sample{ int a; float b; char c; }; union sample s;
When union is declared, the compiler automatically creates largest size variable type to hold variables in the union.
At any time, only one variable can be referred.
Initialization and accessing
Same syntax of structure is used to access a union member.
The dot operator is for accessing members.
The arrow operator ( ->) is used for accessing the members using pointer.
Sample program 1
The following program shows the usage of union of structure.
union sample{ int a; float b; char c; } main ( ){ union sample s = {10, 20.5, "A"}; printf("a=%d",s.a); printf("b=%f",s.b); printf("c=%c",s.c); }
Output
When the above program is executed, it produces the following result −
a = garbage value b = garbage value c = A
Union of structures
A structure can be nested inside a union and it is called union of structures.
It is possible to create a union inside a structure.
Sample Program 2
An another C program which shows the usage of union of structure is given below −
struct x{ int a; float b; }; union z{ struct x s; }; main ( ){ union z u; u.s.a = 10; u.s.b = 30.5; printf("a=%d", u.s.a); printf("b=%f", u.s.b); }
Output
When the above program is executed, it produces the following result −
a= 10 b = 30.5