CSE NotesCSE Notes
Simplifying Complexity

In C, a union is a special data type that allows storing different types of data in the same memory location. Unlike a structure, where each member has its own memory space, all members of a union share the same memory. This means that a union can store only one of its members at a time, but it saves memory by allocating only enough space to hold the largest member.

Key Points about Unions:

  1. Memory Sharing: All members of a union share the same memory space.
  2. Size: The size of a union is determined by the size of its largest member.
  3. Accessing Members: Only one member can hold a value at a time, and when you update one member, it will overwrite the others.

1. Defining a Union

The syntax for defining a union is similar to that of a structure:

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

Example 1: Basic Union

#include <stdio.h>

// Define a union to store different data types
union Data {
    int i;
    float f;
    char str[20];
};

int main() {
    // Declare a union variable
    union Data data;

    // Assign values to the union members
    data.i = 10;
    printf("data.i = %d\n", data.i);

    // Now assign a value to the float member
    data.f = 3.14;
    printf("data.f = %.2f\n", data.f);  // Notice data.i will be overwritten here

    // Now assign a value to the string member
    strcpy(data.str, "Hello, Union!");
    printf("data.str = %s\n", data.str);  // Again, data.i and data.f are overwritten

    return 0;
}

Explanation:

  • Union Declaration: We define a union Data that can hold an integer (i), a float (f), or a string (str).
  • Memory Sharing: The memory used by data will be shared between i, f, and str. At any point, only one of these members will hold a value.
  • Value Assignment: We first assign a value to data.i, then overwrite it with data.f, and finally overwrite both data.i and data.f with data.str.

Output:

data.i = 10
data.f = 3.14
data.str = Hello, Union!

As you can see, after each assignment, the previous value is overwritten because all members share the same memory.

2. Size of a Union

The size of a union is determined by the largest member it contains. This means if you have a union with an integer, a float, and a character array, the size of the union will be the size of the largest member.

Example 2: Checking the Size of a Union

#include <stdio.h>

// Define a union with different types of members
union Data {
    int i;
    float f;
    char str[20];
};

int main() {
    // Declare a union variable
    union Data data;

    // Print the size of the union
    printf("Size of union: %lu bytes\n", sizeof(data));

    return 0;
}

Explanation:

  • Size Calculation: The size of the union is determined by the size of the largest member. In this case, str[20] will determine the size because it is the largest member (typically 20 bytes).

Output:

Size of union: 20 bytes

3. Accessing Union Members

You can access a union’s members in the same way as structures using the dot operator (.). However, remember that when you modify one member of the union, it overwrites the previous value stored in any other member.

Example 3: Accessing Union Members

#include <stdio.h>

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

int main() {
    // Declare a union variable
    union Data data;

    // Assign a value to the integer member
    data.i = 10;
    printf("data.i = %d\n", data.i);

    // Assign a value to the float member, overwriting the previous value of i
    data.f = 3.14;
    printf("data.f = %.2f\n", data.f);

    // Assign a string to the str member, overwriting both i and f
    strcpy(data.str, "Hello, Union!");
    printf("data.str = %s\n", data.str);

    return 0;
}

Output:

data.i = 10
data.f = 3.14
data.str = Hello, Union!

4. Using Union in Structures

You can also use unions inside structures. This allows you to create more flexible data types where you can store different data types but choose only one at a time.

Example 4: Union Inside Structure

#include <stdio.h>

// Define a structure containing a union
struct Student {
    int rollNo;
    union {
        float marks;
        char grade;
    } result;  // Union inside structure
};

int main() {
    struct Student student1;

    // Assign values to the structure members
    student1.rollNo = 101;
    student1.result.marks = 95.5;

    // Print the student's data
    printf("Roll No: %d\n", student1.rollNo);
    printf("Marks: %.2f\n", student1.result.marks);

    // Now, assign a grade to the same union member (overwrites marks)
    student1.result.grade = 'A';

    printf("Grade: %c\n", student1.result.grade);

    return 0;
}

Explanation:

  • Union Inside Structure: The Student structure contains a union named result. The union can store either marks or grade, but not both at the same time.
  • Union Usage: We first assign a value to marks, and later we overwrite it with a value for grade.

Output:

Roll No: 101
Marks: 95.50
Grade: A

5. When to Use a Union

Unions are particularly useful in situations where:

  • You need to store different types of data but only need one type at a time.
  • You want to save memory in a situation where you don’t need all the data types at once (e.g., working with a variable that can hold multiple types of data, such as an input buffer).
  • You are working with protocols or file formats where the data format may change (e.g., a data stream that can be interpreted as different types).

6. Union vs. Structure

  • Structure: In a structure, all members have their own memory, and you can store all the members independently.
  • Union: In a union, all members share the same memory space, and only one member can hold a value at a time.

Example Comparison: Structure vs. Union

#include <stdio.h>

// Structure definition
struct MyStruct {
    int i;
    float f;
    char str[20];
};

// Union definition
union MyUnion {
    int i;
    float f;
    char str[20];
};

int main() {
    // Declare structure and union variables
    struct MyStruct s = {10, 3.14, "Hello"};
    union MyUnion u;

    u.i = 10;
    printf("Union data: i = %d\n", u.i);
    u.f = 3.14;
    printf("Union data: f = %.2f\n", u.f);
    strcpy(u.str, "World");
    printf("Union data: str = %s\n", u.str);

    printf("\nStructure data: i = %d, f = %.2f, str = %s\n", s.i, s.f, s.str);

    return 0;
}

Output:

Union data: i = 10
Union data: f = 3.14
Union data: str = World

Structure data: i = 10, f = 3.14, str = Hello

Conclusion:

  • Unions allow you to save memory when you need to store different types of data but only need one type at a time.
  • Structures are more flexible when you need to store multiple types of data simultaneously.
  • Unions are useful for applications like type-based interpreters, protocols, and flexible data structures.