C Unions

Union is user defined data type used to wrap up one or more variables that may be in different data types into single variable at single memory location. Union is similar to the structure in concepts, except allocating memory for their members.Structure allocates storage space for all its members separately,whereas union allocates one common storage space for all its members.

Difference between structure and union

  • Union allocates one common storage space for all its members
  • In union if any of the data element’s value is changed than the other data element value even changes, i.e. the value of one data element of a union depends on all other data elements.
  • The only major advantage that a union has over structure is to save memory space.
  • Union holds value for one data type which requires larger storage among their members.

Syntax:

Example:

Accessing Union Members

Syntax:

To access member of a union you use the (.) operator, for instance: student1.name