C Programs Tutorials | IT Developer
IT Developer

C Programming - C Unions



Share with a Friend

C Programming - C Unions

C Unions

A union in C is a special data type that allows storing different data types in the same memory location. A union can hold one of its members at a time, meaning all the members share the same memory space. This allows for efficient memory usage, as the memory used by a union is only the size of its largest member.

Syntax of Union

C

union union_name {

    data_type1 member1;

    data_type2 member2;

    // more members

};

  • union_name: The name of the union (optional, can be omitted when using anonymous unions).
  • data_type: The type of the member.
  • member: The variable name.

Memory Allocation in Unions

  • Memory Size: The size of a union is determined by the size of its largest member.
  • Memory Sharing: All members share the same memory space. At any given time, only one member can hold a value, and writing to one member will overwrite the value of the other members.

Example: Union Declaration and Usage

C

#include <stdio.h>

union data {

    int i;

    float f;

    char c;

};

int main() {

    union data d;

    d.i = 10;     // Assigning value to the integer member

    printf("i: %d\n", d.i);

    d.f = 3.14;   // Assigning value to the float member

    printf("f: %f\n", d.f);

    d.c = 'A';    // Assigning value to the character member

    printf("c: %c\n", d.c);

    return 0;

}

Output:

i: 10

f: 3.140000

c: A

Explanation:

  • The union data has three members: an integer (i), a float (f), and a character (c).
  • Each time we assign a value to one member, the previous value stored in the union is overwritten since all members share the same memory location.
  • When we print the value of i, f, and c, we get the value of the most recently assigned member.

Size of a Union

The size of a union is the size of its largest member, but it may also include some padding to align the data properly in memory.

Example: Size of a Union

C

#include <stdio.h>

union data {

    int i;

    float f;

    char c;

};

int main() {

    union data d;

    printf("Size of union: %zu\n", sizeof(d));  // Prints the size of the union

    return 0;

}

Output:

Size of union: 4

Explanation:

  • In this case, the size of the union is 4 bytes because the largest member (int) requires 4 bytes of memory.

Accessing Union Members

A union member can be accessed using the dot (.) operator, similar to structures. However, only one member can hold a value at a time.

Example: Accessing Union Members

C

#include <stdio.h>

union data {

    int i;

    float f;

    char c;

};

int main() {

    union data d;

    d.i = 100;      // Assigning value to integer member

    printf("i: %d\n", d.i);

    d.f = 98.76;    // Assigning value to float member

    printf("f: %.2f\n", d.f);

    d.c = 'Z';      // Assigning value to character member

    printf("c: %c\n", d.c);

    return 0;

}

Output:

i: 100

f: 98.76

c: Z

Explanation:

  • Each member of the union holds a separate value, but only the most recently assigned value is valid.
  • As we assign values to i, f, and c, the previous value is overwritten.

Union vs. Structure

Feature Union Structure
Memory Usage

Members share the same memory location (size of the largest member)

Each member has its own memory location

Access

Only one member can store a value at a time

All members can store a value simultaneously

Size

Size of the largest member

Size of all members combined

Applications of Unions

Unions are useful in situations where:

  1. Memory Optimization: Unions save memory, as they allow storing different types of data in the same memory location.
  2. Multitype Data: Unions are commonly used in situations where a variable can take multiple types, but only one type is used at any given time. For example, in embedded systems, where memory is limited.
  3. Working with Different Formats: They are useful in situations like working with different data formats in file handling, network protocols, or device drivers.

Example: Union for Multitype Data

C

#include <stdio.h>

union data {

    int i;

    float f;

    char c;

};

void printData(union data d, int type) {

    switch (type) {

        case 1: printf("Integer: %d\n", d.i); break;

        case 2: printf("Float: %.2f\n", d.f); break;

        case 3: printf("Character: %c\n", d.c); break;

        default: printf("Invalid type\n"); break;

    }

}

int main() {

    union data d;

    d.i = 5;

    printData(d, 1);  // Print integer

    d.f = 3.14;

    printData(d, 2);  // Print float

    d.c = 'X';

    printData(d, 3);  // Print character

    return 0;

}

Output:

Integer: 5

Float: 3.14

Character: X

Explanation:

  • This example demonstrates how a union can store data of different types (integer, float, character) at different times, and a function can print the stored value based on the type.

Conclusion

  • Unions in C are a powerful tool for efficiently managing memory, especially when you need to store one of several possible data types at a time.
  • While they share the same memory for all members, unions help reduce memory usage by allocating space only for the largest member.
  • Unions are useful for situations involving multitype data or when memory optimization is important, such as in embedded systems or handling different data formats.