0Pricing
C++ Academy · Lesson

Unions and Their Risks

Share memory between types.

Unions and Their Risks is a free C++ Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is a Union?

A union lets several members share the same memory. Only one member is valid at a time, and the union is only as big as its largest member.

#include <iostream>
union Number {
    int i;
    float f;
};
int main() {
    Number n;
    n.i = 42;
    std::cout << n.i << "\n";
}

Size of a Union

Because members overlap, sizeof a union equals the size of its largest member (plus any alignment padding), not the sum.

#include <iostream>
union Mix { char c; int i; double d; };
int main() {
    std::cout << sizeof(Mix) << "\n"; // size of double (often 8)
}

Writing One, Reading Another

Writing one member and reading a different one is the central risk. The bits are reinterpreted, which is usually undefined or surprising.

#include <iostream>
union Bits { int i; float f; };
int main() {
    Bits b;
    b.f = 1.0f;
    std::cout << b.i << "\n"; // reads float bits as int
}

Only One Active Member

The member you last wrote is the only one you may safely read. Track which member is "active" yourself; the union does not remember.

#include <iostream>
union Value { int i; double d; };
int main() {
    Value v;
    v.d = 3.14;        // d is active
    std::cout << v.d << "\n";
}

The Tagged Union Pattern

To use unions safely, pair them with a tag (an enum) that records the active member. This is the manual ancestor of std::variant.

#include <iostream>
struct Tagged {
    enum { Int, Double } tag;
    union { int i; double d; };
};
int main() {
    Tagged t; t.tag = Tagged::Int; t.i = 7;
    if (t.tag == Tagged::Int) std::cout << t.i << "\n";
}

Reading the Right Member

Always branch on the tag before reading. Reading the wrong member produces garbage values.

#include <iostream>
struct Tagged {
    enum { Int, Double } tag;
    union { int i; double d; };
};
void print(const Tagged& t) {
    if (t.tag == Tagged::Int) std::cout << "int " << t.i << "\n";
    else std::cout << "double " << t.d << "\n";
}
int main() { Tagged t{Tagged::Double}; t.d = 2.5; print(t); }

Non-Trivial Members

Putting a member with a constructor or destructor (like std::string) in a union requires manual construction and destruction. This is error-prone, another reason to prefer std::variant.

Anonymous Unions

An anonymous union has no name; its members are accessed directly. It is handy inside a struct, but the same active-member rule applies.

#include <iostream>
struct Packet {
    int kind;
    union { int code; char letter; };
};
int main() {
    Packet p; p.kind = 1; p.code = 99;
    std::cout << p.code << "\n";
}

Why Unions Are Risky

Summary of dangers:

  • No memory of which member is active.
  • Reading an inactive member is undefined behavior.
  • Non-trivial types need manual lifetime management.

When Unions Still Help

Unions remain useful for low-level work: reinterpreting bytes, saving memory in tight embedded code, or matching a fixed binary layout. For everyday "one of several types" data, prefer the safer alternative.

Toward std::variant

std::variant is a type-safe union that tracks the active type for you and throws if you access the wrong one. The rest of this course explores it.

Quick Check

Check your understanding of unions.

Recap

You learned about unions:

  • All members share one block of memory.
  • Only the last-written member is valid to read.
  • Use a tag (enum) to track the active member.
  • Prefer std::variant for safety in modern C++.

Frequently asked questions

Is the “Unions and Their Risks” lesson free?

Yes — the full text of “Unions and Their Risks” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.

What will I learn in “Unions and Their Risks”?

Share memory between types. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Unions and Their Risks” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Scoped enum class
  2. Unions and Their Risks
  3. std::variant
  4. std::visit
← Back to C++ Academy