Union in C

In C, a union is a user-defined data type similar to a structure. However, unlike structures, all members of a union share the same memory location. This means that a union can store a value for only one of its members at any given time.

Declaration and Syntax

                        
union UnionName {
    data_type member1;
    data_type member2;
    ...
};
                    
                    

The memory allocated for a union is equal to the size of its largest member.

Example: Defining and Using a Union

                        
#include <stdio.h>
#include 

union Data {
    int i;
    float f;
    char str[20];
};
    
int main() 
{
    union Data data;

    data.i = 10;
    printf("Integer: %d\n", data.i); // Corrected newline escape sequence

    data.f = 3.14;
    printf("Float: %.2f\n", data.f); // Corrected newline escape sequence

    snprintf(data.str, sizeof(data.str), "Hello, World!");
    printf("String: %s\n", data.str); // Corrected newline escape sequence

    // Note: After assigning a new value, previous values are overwritten
    printf("Integer (overwritten): %d\n", data.i); // Corrected newline escape sequence

       
    return 0;
}
                        
                    

Output:

Integer: 10
Float: 3.14
String: Hello, World!
Integer (overwritten): -484565312 (or garbage value)

Memory Usage

In a union, the memory size is determined by the largest member. For example:

                        
#include <stdio.h>
        
union Example {
    char c;
    int i;
    double d;
};
        
int main() 
{
    printf("Size of union: %zu bytes\n", sizeof(union Example));
    return 0;
}
                        
                    

Output:

Size of union: 8 bytes (on most systems, the size of the largest member, double)

Difference Between Structure and Union

Aspect Structure Union
Memory Allocation Each member has its own memory location. All members share the same memory location.
Size Sum of the sizes of all members. Size of the largest member.
Value Retention All members can hold values simultaneously. Only one member can hold a value at a time.

Key Points