Defining unions in C language

A union is a unique kind of data structure in the C programming language that enables you to store various types of data in the same memory address. The size of a union’s largest member determines how much memory is allotted to it.

The union keyword is used to define a union, which is then followed by the union’s name and a list of its members wrapped in braces.

Syntax:

union union_name {
    member_type member_name1;
    member_type member_name2;
    ...
};

Here, union_name is the name of the union, member_type is the data type of the union member, and member_name is the name of the union member.

Example:

#include <stdio.h>
#include <string.h>

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

int main() {
    union data d;
    
    d.i = 10;
    printf("Value of d.i: %d\n", d.i);
    
    d.f = 3.14;
    printf("Value of d.f: %f\n", d.f);
    
    strcpy(d.str, "hello");
    printf("Value of d.str: %s\n", d.str);

    return 0;
}

Output:

Value of d.i: 10
Value of d.f: 3.140000
Value of d.str: hello

In this example, we have defined a union called data with three members: an integer i, a float f, and a character array str of size 20. We have declared a variable d of type data and assigned values to its members. We have then printed the values of each member using printf statements.

Be aware that when we give one member of a union a value, the value of the other members may change for the worse. When we assign a value to d.f in the example above, the value of d.i is rendered useless. As a result, when utilising unions, we should exercise caution and make sure that we only access the members who have been given legitimate data.