C Programming - Beginner to Brilliance / Structures and Unions

Differences between Structures & Unions

๐Ÿ“Œ Definition Recap

Concept

Description

๐Ÿงฑ Structure (struct)

A collection of variables (members) of different types, stored in separate memory locations, but grouped under a single name.

๐Ÿงฌ Union (union)

Similar to a structure, but all members share the same memory location, and only one member can hold a value at a time.


๐Ÿง  Memory Allocation โ€“ The Core Difference

๐Ÿ” In a struct:

Each member has its own memory location.

struct Sample {
    int a;      // 4 bytes
    float b;    // 4 bytes
    char c;     // 1 byte
};

Total size = sum of all members + padding (usually around 12 bytes)


๐Ÿ” In a union:

All members share the same memory location โ€” the size of the largest member decides the total size.

union Sample {
    int a;      // 4 bytes
    float b;    // 4 bytes
    char c;     // 1 byte
};

Total size = 4 bytes (largest of the three)


๐Ÿ“Š Comparison Table

๐Ÿ”ข Feature

๐Ÿงฑ Structure

๐Ÿงฌ Union

๐Ÿ”ง Memory

Sum of all members' sizes (+ padding)

Size of the largest member

๐Ÿง  Storage

Each member has a separate location

All members share the same memory

๐Ÿ“Œ Active members

All can store and hold values simultaneously

Only one member holds value at a time

๐Ÿ” Value Retention

Value of all members is retained

Assigning a value to one member will overwrite others

๐Ÿ“ฅ Initialization

All members can be initialized

Only the first member can be initialized at declaration

๐Ÿงพ Use Cases

Complex data records (e.g., Employee)

Space-saving when only one field is needed at a time

๐Ÿงฐ Efficiency

Less memory efficient

More memory efficient

๐Ÿงช Syntax

struct Student { int id; };

union Data { int num; };



๐ŸŽฏ When to Use What?

Situation

Use

You need to store multiple pieces of information together

โœ… Use Structure

You need to store only one of many types to save space

โœ… Use Union


๐Ÿ“ฆ Real-Life Analogy

Concept

Analogy

Structure

A lunchbox with compartments: rice, curry, salad โ€” all stored separately but together

Union

A single glass where you can pour either water or juice, but not both at the same time