C Union

Summary: in this tutorial, we will introduce a new type called C union. A C union is similar to a structure that groups related data objects into a single variable. Unlike a structure, a union has a different memory allocation mechanism for its members.

C UnionWhat is a C union?

By definition, union is a type that allows you to store different data types in the same memory location, but not at the same time. A union is a group of data objects that share a single block of memory.

C union syntax

The syntax of union is similar to the syntax of constructing a struct. The following illustrates the syntax of union:

In the C union syntax above, to define a union:

  • First, you start with the union keyword.
  • Second, you define tag for the union.
  • Third, you specify all the members of the union with their types.

To access member of a union you use the ( .) operator. For example:

C Union vs. Struct

In a structure, each member stores data separately. If you change the value of one member of a structure, other member’s values do not change.

However, in a union, all the members share the same block of memory. This block of memory is big enough to store the largest member. Smaller members use as much memory as necessary. If you change value of a member, other members’ values change as well.

If you need to store data in members simultaneously, you must use a structure.

Initialize a union

In ANSI C, there are two ways to initialize a union:

  • You initialize a union to another union with the same type.
  • Alternatively, you can initialize a union by initializing the first member of a union.

The following  program demonstrates how to initialize a union in both ways.

C Union Example

In this example, we have an account structure that could be personal or business account based on the account_type enumeration. If it is a personal account the info member is associated with the person structure, otherwise it is associated with the  company structure.

Just take few minutes go through the code to have a better understanding of using C Union.

In this tutorial, you have learned how to use C union and understand the differences between a union and a structure.