C - union union Introduction

Introduction

C allows the same memory area to be shared by a number of different variables.

We can use a union type to do memory sharing.

The syntax for declaring a union is similar to structures.

A union is usually given a tag name in the same way.

You use the keyword union to define a union.

For example, the following statement declares a union to be shared by three variables:

union MyUnion
{
  float my_Float;
  int *pnum;
  double my_value;
} u1;

This statement declares a union with the tag name MyUnion, which shares memory between a floating-point value my_Float, a pointer to an integer pnum, and a double precision floating-point variable my_value.

The statement defines one instance of the union with a variable name of u1.

You can declare further instances of this union with a statement such as this:

union MyUnion u2, u3;

To assign values to members of u1 and u2, you can write this:

u1.my_Float = 2.5;
u2.my_Float = 3.5*u1.my_Float;

The size of an instance of a union is the memory required for the largest member.