C Union

In C, a union is a special data type that allows you to store different types of data in the same memory location. Unlike a struct, where each member has its own memory space, a union shares the same memory space for all of its members.

Syntax:


union union_name {
    data_type member1;
    data_type member2;
    data_type member3;
    // more members
};

How Unions Work

Unions allow you to store different types of data in the same memory location, but only one of the members can hold a value at any given time. This is why, if you assign a new value to one member, it overwrites the previous value in the union.

Process of Union Work

1. The memory for a union is shared between all its members.

2. You can only use one member at a time, meaning the data stored in one member can overwrite data stored in another member.

3. Unions are useful when you know that only one member will be used at a time, so you save memory by reusing the same space.

Declaring and Accessing Union Members

You can access the members of a union just like you would with a struct, using the . (dot) operator. However, remember that only one member holds a valid value at a time.

Example:


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

union Employee {
    char name[20];
    int age;
    float salary;
   
};

int main() {
    union Employee emp;
    
    // Storing a string (this overwrites the float)
    strcpy(emp.name, "John");
    printf("emp.name: %s\n", emp.name);

    // Storing an integer
    emp.age = 35;
    printf("emp.age: %d\n", emp.age);

    // Storing a float (this overwrites the integer)
    emp.salary = 10500.50;
    printf("emp.salary: %.2f\n", emp.salary);

  
    // The previous members are no longer valid
    printf("emp.age (overwritten): %d\n", emp.age);  // This will not be 35
    printf("emp.salary (overwritten): %.2f\n", emp.salary); 

    return 0;
}

Output:

emp.name: John
emp.age: 35
emp.salary: 10500.50
emp.age (overwritten): 1176769024
emp.salary (overwritten): 10500.50

Differences Between struct and union

1. In a struct, each member gets its own memory space, so the total size of the struct is the sum of the sizes of its members. In a union, all members share the same memory space, so the size of the union is equal to the size of its largest member.

2. In a struct, all members can hold values at the same time. In a union, only one member can hold a valid value at any time.