0
0
Cprogramming~5 mins

Union basics

Choose your learning style9 modes available
Introduction

A union lets you store different types of data in the same memory space, but only one at a time.

When you want to save memory by sharing space for different data types.
When a variable can hold different types of values but only one at a time.
When you need to interpret the same data in multiple ways.
When working with hardware or protocols that use the same bytes for different meanings.
Syntax
C
union UnionName {
    type1 member1;
    type2 member2;
    // more members
};

All members share the same memory location.

The size of the union is the size of its largest member.

Examples
This union can hold either an int or a float, but not both at the same time.
C
union Data {
    int i;
    float f;
};
This union can store a char, int, or double, sharing the same memory space.
C
union Value {
    char c;
    int i;
    double d;
};
Sample Program

This program shows how a union stores either an int or a float in the same place. When we change the float, the int value changes because they share memory.

C
#include <stdio.h>

union Number {
    int i;
    float f;
};

int main() {
    union Number num;

    num.i = 42;
    printf("Integer: %d\n", num.i);

    num.f = 3.14f;
    printf("Float: %.2f\n", num.f);

    // Note: after assigning to num.f, num.i value is overwritten
    printf("Integer after float assignment: %d\n", num.i);

    return 0;
}
OutputSuccess
Important Notes

Only one member of a union can hold a meaningful value at a time.

Changing one member overwrites the others because they share memory.

Use unions carefully to avoid confusing bugs.

Summary

Unions share memory for all members, saving space.

Only one member can be used at a time.

Useful for memory-efficient storage and interpreting data in different ways.