C Programming Tutorial 0/65 lessons ~6 min read Lesson 35

    Unions

    A union shares one memory block among members — size equals largest member; only one member active at a time.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    A union shares one memory block among members — size equals largest member; only one member active at a time.

    Understanding the topic

    Memory sharing Writing to one member overwrites others.

    Use cases Variant types, protocol fields, embedded registers.

    • Memory sharing — Writing to one member overwrites others.
    • Use cases — Variant types, protocol fields, embedded registers.

    Step-by-step explanation

    1. Memory sharing — Writing to one member overwrites others.
    2. Use cases — Variant types, protocol fields, embedded registers.

    Syntax reference

    Syntax reference:

    c
    union Tag { type a; type b; };

    Informative example

    Example program:

    c
    #include <stdio.h>
    union Data { int i; float f; };
    int main(void) {
    union Data d;
    d.i = 10;
    printf("%d\n", d.i);
    return 0;
    }

    Output

    10

    Execution workflow

    1Unions — step by step
    1 / 2

    Memory sharing

    Writing to one member overwrites others.

    Best practices

    • Enable warnings: gcc -Wall -Wextra -std=c11 source.c -o app
    • Give every variable a defined value before it is read.
    • Stay inside array bounds — C will not stop you from over-running a buffer.

    Common mistakes

    • Reading uninitialized storage — behavior is undefined.
    • Dismissing compiler warnings instead of fixing root causes.
    • Ignoring NULL returns from malloc, fopen, and similar APIs.

    Hands-on exercise

    Practice problems:

    • Store int or float in union
    • Compare struct vs union size

    Summary

    Unions in C — Overlapping members sharing one storage region.

    Ready to mark this lesson complete?Track your journey across the entire course.