Struct and union
- C course
- Intermediate
- Lesson 38/116
- 5 min
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.
Practice 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;.
Starter code
#include <stdio.h>
// Define enum Type, union Value and struct TaggedValue
// In main declare tv, tag as INT_T, set i to 42
// Select type with switch and print
int main(void) {
return 0;
}Sample 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;
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Tagged union member access
struct TaggedValue tv;
tv.type = INT_T;
tv.value____ = 42;
struct TaggedValue tv;
tv.type = INT_T;
tv.value.i = 42;
Explanation: tv.value is a value; access with .i.
2 Match the tagged union parts
| Term | Meaning |
|---|---|
enum Type type |
Tag field |
union Value value |
Value field |
switch (tv.type) |
Type selection |
tv.value.i |
int member access |
3 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 Correct answer
Explanation: The tag tells which union member is active.