Union is a concept borrowed from structures and therefore follows the same syntax as structure. However, there is a major distinction between them in terms of memory storage. In structure, each member or element has its own memory location Whereas all the members of the union use the same memory location.Like structure,a union can be declared using the keyword Union as follow:-
1 2 3 4 5 6 7 |
union union_name { data_type member1; data_type member2; --------- -------- --------- -------- }; |
For example:-
1 2 3 4 5 6 |
union data { char a; int b; float c; }; |
After defining a union format we can declare variable of that type.A union variable declaration is same as declaration of structure variable .A general form is:-
1 2 3 4 5 6 7 |
union data { char a; int b; float c; }; union data d1; |
The compiler allocates a piece of memory that is large enough to hold that largest variable type in the union. In the declaration above, the member c(float) is the largest among the member/So all three variables shares the same address. For access the union member, we can use the same syntax that we use for structure members. for example:-
1 2 3 |
d1.a d1.b d1.c |
Note:- Union creates a memory location that can be used by any one of its members at a time.When a different member is assigned a new value supersedes the previous member value.
C Code Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <stdio.h> union data { char a; int b; float c; }; union data d1; void main() { printf("Enter value "); scanf("%c",&d1.a ); printf("\n Enter value is %c",d1.a); } |