C
Struct and union
Learn to use union inside a struct.
Struct and union
By putting a union inside a struct, you create a tagged union. The tag tells which union member is active. This is the standard pattern for safe union use.
Example: enum Type { INT_T, FLOAT_T };, union Value { int i; float f; }; and struct TaggedValue { enum Type type; union Value value; };. You set the tag with tv.type = INT_T; and the value with tv.value.i = 42;. When reading, you first check type and read the right member. This pattern is common for data formats, protocol messages and AST nodes.
Type selection with switch
To read a tagged union safely, you check the tag with a switch. Each case reads the matching member. This prevents reading the wrong member.
Example: switch (tv.type) { case INT_T: printf("%d\n", tv.value.i); break; case FLOAT_T: printf("%f\n", tv.value.f); break; }. Without break you get fall-through; that's usually a bug. A default branch catches unexpected tags. This pattern is the standard read form for tagged unions in real-world code; interpreters and serializers use it.
Exercise Print with a tagged union
Define enum Type { INT_T, FLOAT_T };, union Value { int i; float f; }; and struct TaggedValue { enum Type type; union Value value; };. In main, write struct TaggedValue tv;; set tv.type = INT_T; and tv.value.i = 42;. Add switch (tv.type) with case INT_T: printf("%d\n", tv.value.i); break;.
Show example solution
#include <stdio.h>
enum Type { INT_T, FLOAT_T };
union Value { int i; float f; };
struct TaggedValue { enum Type type; union Value value; };
int main(void) {
struct TaggedValue tv;
tv.type = INT_T;
tv.value.i = 42;
switch (tv.type) {
case INT_T: printf("%d\n", tv.value.i); break;
}
return 0;
}
Test yourself
-
Tagged union member access
struct TaggedValue tv;
tv.type = INT_T;
tv.value____ = 42;
Show answer
struct TaggedValue tv;
tv.type = INT_T;
tv.value.i = 42;
-
Match the tagged union parts
- enum Type type
- Tag field
- union Value value
- Value field
- switch (tv.type)
- Type selection
- tv.value.i
- int member access
-
Why is a tag used in a tagged union?
- For a compiler error
- For memory savings
- For faster access
- To know which member is active
Show answer
To know which member is active — The tag tells which union member is active.
Next lesson: typedef enum