YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Designing dataChapter 33 of 73

Unions and tagged data

Use shared storage for alternatives and maintain a clear contract connecting an explicit tag to the selected payload.

5 min readCore conceptsC17 baseline
Offline reading
In this chapter8 sections
0% through this chapter

Sometimes a value can take one of several forms. A union lets those forms share storage. A separate tag can record which form the program intends, but the program must keep the tag and stored data consistent.

1. Alternatives share one storage region

A union is large enough for its largest member and can include padding. Its members overlap; they are not independent slots like the members of a structure. Writing ratio does not preserve a separately stored count value for later retrieval. The example saves the count in another object before selecting the other representation.

C17 · illustrative fragment
union Number { int count; double ratio; };
union Number value = {.count = 7};
int count = value.count;
value.ratio = 0.5;
double ratio = value.ratio;

Think of one workspace arranged for one of several jobs. Its limit is that C does not put an automatic label on that workspace telling future code which job was selected. A raw union value supplies shared storage, not a self-checking variant.

2. A tag records the program’s interpretation

Complete C17 program
#include <assert.h>

enum ReadingKind { READING_COUNT, READING_RATIO };
struct Reading {
    enum ReadingKind kind;
    union { int count; double ratio; } data;
};

static int count_or_zero(const struct Reading *reading)
{
    if (reading->kind == READING_COUNT) return reading->data.count;
    return 0;
}

int main(void)
{
    struct Reading item = {.kind = READING_COUNT, .data = {.count = 7}};
    assert(count_or_zero(&item) == 7);
    item = (struct Reading){.kind = READING_RATIO, .data = {.ratio = 0.5}};
    assert(count_or_zero(&item) == 0);
    return 0;
}
A tagged reading
kind
READING_COUNT
shared payload
data.count = 7
The tag is separate from the union. The program must keep this tag/member relationship consistent; the language does not enforce it.

The tag or discriminant belongs to the enclosing structure. The contract says a count tag permits reading the count member; a ratio tag selects the ratio member. All constructors, updates, copies, and readers must respect that invariant. Updating a tag alone is not enough to initialize its selected payload.

The compound-literal update above supplies a complete new tagged value; the next lesson explains that syntax. It still does not provide atomic synchronization between threads. A pointer payload would also need an ownership contract specific to the selected alternative.

3. Reading another member is not numeric conversion

In C, reading a member other than the one most recently written reinterprets the corresponding object representation under the union rules. The result depends on representations and can involve a trap representation. Do not teach value.count after storing value.ratio as a portable way to convert a floating value to an integer. A numeric conversion uses C’s value-conversion rules instead.

This permission is specific to the relevant union access rules. Freely casting an unrelated pointer and dereferencing it can still violate alignment and effective-type requirements. A union is not a general escape hatch from all aliasing rules, and its bytes are not a universal hardware-independent encoding.

4. A common prefix has a narrow special rule

Optional: common initial sequence
C17 · illustrative fragment
struct CountRecord { int kind; int count; };
struct RatioRecord { int kind; double ratio; };
union Record { struct CountRecord count; struct RatioRecord ratio; };
union Record item = {.count = {1, 7}};
int kind = item.ratio.kind;

These two structure members of a union begin with compatible int kind members. When the union currently contains one of those structure types, C permits inspecting the common initial part under the common-initial-sequence rule, where a declaration of the completed union type is visible. The following int and double members do not extend that compatible prefix. This is a specified exception, not permission to read every alternate member.

5. Anonymous members change access syntax

C11 added anonymous structure and union members using an untagged structure or union definition with no member declarator. Their members can be accessed through the enclosing object without an extra member name. This can shorten a tagged-union interface, but it does not create an automatic tag, extend payload lifetimes, or validate which member should be read. The earlier example deliberately names the union member data to make the grouping visible.

Primary references and further reading

Before you move on

  • Union members share storage rather than each receiving separate simultaneous storage.
  • A tag can identify which interpretation the program intends.
  • The program must preserve the relationship between the tag, stored data, and permitted accesses.
Keep these ideas separate
Tag value / Enforced invariant
Writing a tag does not automatically initialise the matching union member or validate a contradictory record.
Explain it in your own words

What should an update do to keep a tagged union’s chosen form and data consistent?

Optional: say it aloud or keep a note. You can continue whenever you are ready.

Check your understanding

Optional. Answers are not saved or sent, and reading stays unrestricted.

In a tagged-union design, who keeps the tag consistent with the intended payload?
Read the explanation for every choice
  1. The program, through its construction and access contract.

    ✓ Correct reasoning. Assigning a union member does not automatically update a separate tag field.

  2. The union updates every separate tag automatically.

    C provides no such automatic relationship for an ordinary separate tag field.

  3. No tag is needed because every union member has separate storage.

    Union members share storage; the intended interpretation needs a clear contract.

C17

Ready for the next idea?

Mark this chapter as read whenever you feel ready.

CHAPTER 33 / 73

In this chapter

Unions and tagged data

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping