C Union

What is 'union' in C?

Union Declaration

Union is a composite data type that allows you to store different types of data in the same memory location. It is similar to a structure ('struct') in that it can hold multiple variables of different data types, but unlike a 'struct', a union can only store the value of one of its members at a time. This means that the size of a union is determined by the size of its largest member.

Here's how you declare a union in C:

union union_name {
    data_type member1;
    data_type member2;
    // Additional members
};

Breakdown of mentioned union syntax:

'union_name': The name of the union.

'data_type': The data type of each member.

You can have multiple members in a union, Here's an example of how you might use a union:

c Copy Code
#include <stdio.h>
#include <string.h>

// Define a union named Data
union Data {
    int i;
    float f;
    char str[20];
};

int main() {
    union Data data;

    // Store an integer in the union
    data.i = 10;
    printf("Integer value: %d\n", data.i);

    // Store a floating-point number in the same union
    data.f = 3.14;
    printf("Float value: %f\n", data.f);

    // Store a string in the union
    strcpy(data.str, "Hello, Friend!");
    printf("String value: %s\n", data.str);

    return 0;
}

In this program, we define a union called 'Data' with three members: an integer ('i'), a floating-point number ('f'), and a character array ('str'). We then demonstrate how to store and access different types of data in the same union. Please note that when you assign a value to one member of the union, it may affect the value of other members because they all share the same memory location. This is a key characteristic of unions.

Output:
Integer value: 10
Float value: 3.140000
String value: Hello, Friend!

As you can see, each time we assign a value to a member of the union, it overwrites the previous value in the union's memory. This is why the values of the integer, float, and string are displayed correctly in the output.

What is New?

We have just updated this website & still working on adding new content & updating existing features.