0
0
CHow-ToBeginner · 4 min read

How to Use Union with Structure in C: Syntax and Example

In C, you can use a union to store different data types in the same memory space, and a struct to group variables. Combining them means you can have a union inside a struct or vice versa, allowing flexible data storage with shared memory for some members.
📐

Syntax

A union allows storing different data types in the same memory location, while a structure groups variables together with separate memory for each member. You can define a union inside a struct or a struct inside a union.

Example syntax:

struct Example {
    int id;
    union {
        int intValue;
        float floatValue;
    } data;
};

Here, data is a union inside the structure Example. The union members share the same memory, so only one can hold a value at a time.

c
struct Example {
    int id;
    union {
        int intValue;
        float floatValue;
    } data;
};
💻

Example

This example shows how to use a union inside a struct to store either an integer or a float value, along with an ID. It demonstrates how the union shares memory and how to access its members.

c
#include <stdio.h>

struct Example {
    int id;
    union {
        int intValue;
        float floatValue;
    } data;
};

int main() {
    struct Example ex;
    ex.id = 1;

    ex.data.intValue = 42;
    printf("ID: %d, intValue: %d\n", ex.id, ex.data.intValue);

    ex.data.floatValue = 3.14f;
    printf("ID: %d, floatValue: %.2f\n", ex.id, ex.data.floatValue);

    // Note: intValue now holds garbage because floatValue overwrote the memory
    printf("ID: %d, intValue after floatValue set: %d\n", ex.id, ex.data.intValue);

    return 0;
}
Output
ID: 1, intValue: 42 ID: 1, floatValue: 3.14 ID: 1, intValue after floatValue set: 1078523331
⚠️

Common Pitfalls

  • Overwriting union members: Since all union members share the same memory, writing to one member overwrites the others.
  • Accessing inactive member: Reading a union member different from the last written one leads to undefined or garbage values.
  • Not tracking active member: You must keep track of which union member is currently valid, often by using an extra variable or enum.

Example of wrong and right usage:

c
#include <stdio.h>

struct Example {
    int id;
    enum {INT, FLOAT} type;
    union {
        int intValue;
        float floatValue;
    } data;
};

int main() {
    struct Example ex;
    ex.id = 2;

    // Wrong: no type tracking
    ex.data.intValue = 10;
    ex.data.floatValue = 5.5f; // overwrites intValue
    printf("Wrong intValue: %d\n", ex.data.intValue); // garbage

    // Right: track type
    ex.type = INT;
    ex.data.intValue = 10;
    if (ex.type == INT) {
        printf("Right intValue: %d\n", ex.data.intValue);
    }

    ex.type = FLOAT;
    ex.data.floatValue = 5.5f;
    if (ex.type == FLOAT) {
        printf("Right floatValue: %.1f\n", ex.data.floatValue);
    }

    return 0;
}
Output
Wrong intValue: 1092616192 Right intValue: 10 Right floatValue: 5.5
📊

Quick Reference

Tips for using unions with structures in C:

  • Use a union inside a struct to save memory when variables are mutually exclusive.
  • Always track which union member is active using an extra variable or enum.
  • Access only the last written union member to avoid undefined behavior.
  • Use typedef to simplify complex union/struct declarations.

Key Takeaways

A union inside a struct shares memory among its members, so only one member holds valid data at a time.
Always track which union member is currently active to avoid reading invalid data.
Use unions with structs to save memory when you need to store different types but never at the same time.
Accessing a union member different from the last written one causes undefined or garbage values.
Combining union and struct allows flexible and memory-efficient data organization.