Unions and tagged data
Use shared storage for alternatives and maintain a clear contract connecting an explicit tag to the selected payload.
In this chapter8 sections
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.
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
#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;
}
- kind
- READING_COUNT
- shared payload
- data.count = 7
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
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
- WG14 N1570 — public C11 committee draft: 6.5.2.3p3–p6 (including footnote 95), 6.7.2.1. Stable core rules used for the C17 baseline; this is not the final ISO publication.
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.
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.
Read the explanation for every choice
- The program, through its construction and access contract.
✓ Correct reasoning. Assigning a union member does not automatically update a separate tag field.
- The union updates every separate tag automatically.
C provides no such automatic relationship for an ordinary separate tag field.
- 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.