Skip to main content

Unions in C

Introduction to Unions in C

Unions in C are a special data type that allow you to store different types of data in the same memory location. Similar to structures, unions provide an efficient way of using the same memory location for multiple purposes. A union can be defined in C using the union keyword.

Defining Unions

You can define a union in C like this:

union Data {
int i;
float f;
char str[20];
};

In the example above, we're defining a union named Data. This union can store an integer (i), a float (f), or a string (str). The size of the union will be the size of the largest data type member in the union. In this case, str[20] has the largest size, so the size of the union is 20 bytes.

Accessing Union Members

To access any member of a union, we use the dot (.) operator. Here is an example:

union Data data;

data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");

printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);

But there's a catch. A union can only store one member's data at a time. So, in the example above, the values of data.i and data.f are corrupted because we're assigning a new value to data.str. The final output will only show the value of data.str correctly.

Why Use Unions?

Unions are used when you want to save memory by using the same memory location for storing different types of data. They are also used in hardware-interaction operations, such as implementing a cycle buffer or reading/writing to a certain memory location.

When to Use Unions?

Use unions in C when you need to achieve any of the following:

  1. To save memory by using the same memory space for storing different types of data.
  2. To access a particular memory location using different data types.

Key Points to Remember

  • A union can have many members, but only one member can contain a value at any given time.
  • Unions provide an efficient way to use the same memory location for multiple purposes.
  • The size of a union is equal to the size of its largest data member.

In conclusion, unions in C allow you to store different types of data in the same memory location. They are a powerful tool for managing memory efficiently and interacting with hardware. However, they should be used wisely because they can only hold one member's data at a time.