Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / C Programming Tutorial / Chapter 4: User-Defined Types & Memory Management
C ⏱ 10 min read

Unions and Differences with Structs

Unions look almost identical to structures, but handle memory allocation in a completely different way.

What is it?

A `union` is a user-defined data type where all members share the exact same memory location.

Why is it used?

Conserves memory in resource-constrained embedded systems and creates polymorphic variable types.

Detailed Explanation

Struct vs Union: • Struct: Each member gets its own separate memory address. Total size is at least the sum of all member sizes (plus padding). • Union: All members share the same single memory location! The size of a union is equal to the size of its largest member. • Only ONE member of a union can hold a valid value at any given time. Writing to one member overwrites the others.

Syntax Structure

Syntax Blueprint
union Data {
    int i;
    float f;
    char str[20];
};

Code Example

C Code
#include <stdio.h>

struct StructDemo {
    int integer_val; // 4 bytes
    float float_val; // 4 bytes
    char char_val;   // 1 byte
};

union UnionDemo {
    int integer_val; // 4 bytes
    float float_val; // 4 bytes
    char char_val;   // 1 byte (All share same 4 bytes!)
};

int main() {
    printf("sizeof(StructDemo): %zu bytes\n", sizeof(struct StructDemo));
    printf("sizeof(UnionDemo):  %zu bytes (Memory Shared!)\n", sizeof(union UnionDemo));
    
    union UnionDemo u;
    u.integer_val = 65;
    printf("\nSet integer_val = 65:\n");
    printf("u.integer_val = %d\n", u.integer_val);
    printf("u.char_val    = %c (ASCII 65 is 'A')\n", u.char_val);
    
    return 0;
}

Explanation of the Code

• The struct takes at least 12 bytes (due to memory alignment padding). • The union takes only 4 bytes (size of largest member). • Setting `integer_val = 65` simultaneously reflects as character `'A'` in the shared memory byte.

Expected Output

sizeof(StructDemo): 12 bytes sizeof(UnionDemo): 4 bytes (Memory Shared!) Set integer_val = 65: u.integer_val = 65 u.char_val = A (ASCII 65 is 'A')

Real-World Application

Used in network protocol packets where a payload can be either an IP address, domain string, or error code depending on packet type.

Common Mistakes to Avoid

• Trying to store values in multiple union members simultaneously (the second write overwrites the first). • Confusing unions with structs.

Quick Practice Challenge

Declare a union with `int a` and `double b`. Print `sizeof` of the union.

Key Takeaways

• Union members share the exact same memory location. • Size of a union equals the size of its largest member. • Ideal for memory-critical microcontrollers and protocol parsers.