Union in C

Union is a collection of variables of different data types. Union is useful for representing logically related information of different data types.
Union and Structure are almost similar in terms of defining and declaring them but the basic differance between structure and union is that in structure memory is allocated seperately for each member while in union only one memory block is allocated for all members.

In union all members share one common memory space. Compiler allocates memory space such that it can accommodate largest member of the union.
In union only one data member can be accessed at a time because all data member share one common memory. 

union union_name
   datatype variable1;
   datatype variable2;
   datatype variableN;

Union can be declared using union keyword.
Members of the union must be enclosed between curly brackets and declaration of union must end with semicolon.

union Item
    int qty;
      float price;
Item is a union having two members declared inside it.

Variable of union can be declared using union keyword and union name.

union union_name Var1,Var2,Var3;
union Item I1, I2, I3; 
In above example union Item having two members.
Member Name Data Type Size in Byte
qty int 2
price float 4
Total Memory Occupied 4

Here largest memory occupied is 4 bytes so 4 bytes allocated to each union variable I1, I2 and I3.
Members of the union can be accessed using variable name followed by dot (.) operator followed by member name.



Download Projects

Download Programs