Union in C
Definition
 Unions are conceptually similar
to structures.
 The syntax of union is also similar to
that of structure.
 The only differences is in terms of
storage.
 In structure each member has its own
storage location, whereas all members
of union uses a single shared memory
location which is equal to the size of its
largest data member.
 This implies that although a union may
contain many members of different types, it
cannot handle all the members at same
time. A union is declared
using union keyword.
 This declares a variable It1 of type union item.
This union contains three members each with a
different data type. However only one of them can be
used at a time. This is due to the fact that only one
location is allocated for a union variable, irrespective of
its size. The compiler allocates the storage that is large
enough to hold largest variable type in the union. In
the union declared above the member x requires 4
bytes which is largest among the members in 16-bit
Accessing a Union Member
 Syntax for accessing union member
is similar to accessing structure
member,
Complete Example for Union
here, the values
of a and b get
corrupted and only
variable c prints the
expected result. This
is because in union,
the memory is
shared among
different data types.
Hence, the only
member whose
value is currently
stored will have the
memory.

Union in c language

  • 1.
  • 2.
    Definition  Unions areconceptually similar to structures.  The syntax of union is also similar to that of structure.  The only differences is in terms of storage.  In structure each member has its own storage location, whereas all members of union uses a single shared memory location which is equal to the size of its largest data member.
  • 4.
     This impliesthat although a union may contain many members of different types, it cannot handle all the members at same time. A union is declared using union keyword.  This declares a variable It1 of type union item. This union contains three members each with a different data type. However only one of them can be used at a time. This is due to the fact that only one location is allocated for a union variable, irrespective of its size. The compiler allocates the storage that is large enough to hold largest variable type in the union. In the union declared above the member x requires 4 bytes which is largest among the members in 16-bit
  • 5.
    Accessing a UnionMember  Syntax for accessing union member is similar to accessing structure member,
  • 6.
    Complete Example forUnion here, the values of a and b get corrupted and only variable c prints the expected result. This is because in union, the memory is shared among different data types. Hence, the only member whose value is currently stored will have the memory.