Unions in C

A union in C is a special data type that allows multiple members to share the same memory location. Unlike structures, where every member has its own memory, union members overlap in memory — only one value can exist at a time.

What is a Union?

A union is a user-defined datatype similar to a structure but with one key difference: All members share the same memory.

Syntax of Union

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

Union vs Structure

Unions save memory — best for programs dealing with multiple data formats stored at different times.

Where Unions Are Used?

5 Practical Examples of Unions

Example 1 – Basic Union Usage

#include <stdio.h>

union Data {
    int i;
    float f;
};

int main() {
    union Data d;
    d.i = 10;
    printf("Int: %d\n", d.i);

    d.f = 3.14;
    printf("Float: %.2f", d.f);

    return 0;
}

Example 2 – Only Latest Value Survives

#include <stdio.h>

union Example {
    int x;
    char y;
};

int main() {
    union Example e;

    e.x = 100;
    e.y = 'A';

    printf("Integer (corrupted): %d\n", e.x);
    printf("Char: %c", e.y);

    return 0;
}

Example 3 – Union Size

#include <stdio.h>

union Test {
    int a;
    double b;
    char c;
};

int main() {
    printf("Size = %lu bytes", sizeof(union Test));
    return 0;
}

Example 4 – Using Union for Different Formats

#include <stdio.h>

union Number {
    int integer;
    float decimal;
};

int main() {
    union Number n;

    n.integer = 500;
    printf("Integer: %d\n", n.integer);

    n.decimal = 10.75;
    printf("Decimal: %.2f", n.decimal);

    return 0;
}

Example 5 – Union Inside Structure

#include <stdio.h>

struct Student {
    char name[20];
    union {
        int roll;
        float percentage;
    } info;
};

int main() {
    struct Student s = {"Sourav"};

    s.info.roll = 101;
    printf("Name: %s\nRoll: %d", s.name, s.info.roll);

    return 0;
}

Practice Questions

  1. What is a union? How is it different from a structure?
  2. Explain memory allocation in unions.
  3. Why can a union store only one value at a time?
  4. Give real-life applications of unions.
  5. Create a union to store integer, float, and char values.
Practice Task: Create a program using a union to store temperature readings in both Celsius and Fahrenheit. Show how assigning one value overwrites the other.