Union In C Programming

Union Definition

Unions are user-defined data type in C, Union is a data type in C programming that allows different data types to be stored in the same memory locations.

You can define a union with many members, but only one member can contain a value at any given time.

We can access only one member of union at a time. We can’t access all member values at the same time in union

Unions are conceptually similar to Structures. The only difference between them is memory allocation. Structure allocates storage space for all its members separately; Whereas, Union allocates one common storage space for all its members.

Defining a Union

union tagname
{
datatype member1;
datatype member2;
.......
.......
};

About union

  • Union is the collection of different data types.
  • If we want to use Union use of ‘union’ keyword is mandatory.
  • Every declaration done inside a union is called member.
  • A single memory location is shared among the members of the Union.
  • The biggest in size among the members decides the size of the Union.

Initializing a union

 union Employee{
   int age;
   long salary;
 } employee={20000};

Example:



Output:

  Memory size occupied by data : 20

Accessing Union Members

Union members can be accessed the same way as structure members are accessed. To access any member of a union, we use the member access operator (.).



Output:

 data.i : 1917853763
 data.f : 4122360580327794900000000000000.000000
 data.str : C Programming

Difference between Structure and Union

StructureUnion
1For defining structure use struct keyword.For defining union we use union keyword
2Structure occupies more memory space than union.Union occupies less memory space than Structure.
3In Structure we can access all members of structure at a time.In union we can access only one member of union at a time.
4Structure allocates separate storage space for its every members.Union allocates one common storage space for its all members. Union find which member need more memory than other member, then it allocate that much space