CKTIS / C
Tagged union in C
A tagged union pairs an `enum` field with a `union` payload. The tag tells you which alternative was stored and which member to read.
Version: ISO C23; implementation support may vary
Syntax
enum Kind { CPU_MS, REQUESTS };
struct Metric {
enum Kind kind;
union { int cpu_ms; unsigned requests; } value;
};
struct Metric m = { .kind = CPU_MS, .value = { .cpu_ms = 120 } };
/* Equivalent initialization with a chained designator: */
struct Metric same = { .kind = CPU_MS, .value.cpu_ms = 120 };A tagged union is a pattern, not a separate C language construct. A struct holds the enum tag kind and the union payload value. The union's members share storage: at most one member's value is stored at a time. A type name such as Metric in struct Metric is not the tag stored in the object.
The program must maintain the invariant: CPU_MS means a value was stored in cpu_ms, and REQUESTS means it was stored in requests. When changing variants, write both the new payload and its matching tag. Use switch on kind before reading the corresponding member. default rejects an unrecognized tag but cannot detect a mismatch behind a recognized one. Reading a different member can reinterpret the object representation and is not a portable substitute for value conversion.
In a designated initializer, .member = value selects a member by name rather than position. In .value = { .cpu_ms = 120 }, the inner braces apply to the value union, so { .cpu_ms = 120 } selects cpu_ms. The chained designator .value.cpu_ms = 120 selects the same nested member. This syntax has been standard since C99; it does not require C23.
NULL, available from <stddef.h>, is a macro that expands to a null pointer constant, not an element count. print_metrics(NULL, 0) explicitly handles the empty case without accessing any element; print_metrics(NULL, 1) rejects inconsistent arguments. For a non-null pointer, the caller must ensure that n initialized elements are alive and accessible.
Examples
#include <stddef.h>
#include <stdio.h>
enum Kind { CPU_MS, REQUESTS };
struct Metric {
enum Kind kind;
union {
int cpu_ms;
unsigned requests;
} value;
};
static void print_metrics(const struct Metric *metrics, size_t n)
{
if (metrics == NULL) {
puts(n == 0 ? "empty" : "invalid input");
return;
}
for (size_t i = 0; i < n; ++i) {
switch (metrics[i].kind) {
case CPU_MS:
printf("cpu_ms=%d\n", metrics[i].value.cpu_ms);
break;
case REQUESTS:
printf("requests=%u\n", metrics[i].value.requests);
break;
default:
puts("invalid tag");
return;
}
}
}
int main(void)
{
const struct Metric metrics[] = {
{ .kind = CPU_MS, .value = { .cpu_ms = 120 } },
{ .kind = REQUESTS, .value.requests = 7u }
};
print_metrics(metrics, sizeof metrics / sizeof metrics[0]);
print_metrics(NULL, 0);
print_metrics(NULL, 1);
return 0;
}Result
cpu_ms=120 requests=7 empty invalid input
The program prints two values from different variants, then shows how a zero count and a positive count are handled with `NULL`.
Related lessons
- C · Lesson 78 · Advanced · Version: 3