Unions in C

In C programming language, a union is a user-defined data type that allows multiple variables of different data types to share the same memory space. Unions enable the programmer to create a single variable that can be interpreted as different data types.

To declare a union in C, you need to define its members and their data types. Here’s an example of how to declare a union in C:

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

In this example, we declare a union named “Data” that has three members: an integer named “i”, a float named “f”, and a character array named “str” with a maximum size of 20 characters.

We can create variables of the union type by using the “union” keyword followed by the union name. Here’s an example of how to create a variable of the “Data” union type:

union Data d1;

In this example, we create a variable named “d1” of the “Data” union type.

We can access the members of a union variable using the dot operator “.”. However, only one member of the union can be accessed at a time. Here’s an example of how to access the members of a “Data” union variable:

union Data d1;

d1.i = 10;
printf("d1.i: %d\n", d1.i);

d1.f = 3.14;
printf("d1.f: %.2f\n", d1.f);

strcpy(d1.str, "Hello");
printf("d1.str: %s\n", d1.str);

In this example, we create a “Data” union variable named “d1” and initialize its members with the values 10, 3.14, and “Hello”. We then use the dot operator “.” to access the members of the “d1” variable and print them to the console using printf().

We can also use pointers to manipulate union variables in C. Here’s an example of how to use a pointer to access the members of a “Data” union variable:

union Data d1;
union Data *ptr = &d1;

ptr->i = 10;
printf("d1.i: %d\n", ptr->i);

ptr->f = 3.14;
printf("d1.f: %.2f\n", ptr->f);

strcpy(ptr->str, "Hello");
printf("d1.str: %s\n", ptr->str);

In this example, we create a “Data” union variable named “d1” and a pointer named “ptr” that points to the “d1” variable. We use the -> operator to access the members of the “d1” variable through the pointer and print them to the console using printf().

Unions in C are a powerful feature that enable the programmer to create a single variable that can be interpreted as different data types. However, it is important to use unions carefully to avoid type compatibility issues and memory alignment and padding issues.