🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Tagged Unions Quiz Interview Prep
Nested aggregates, the tag pattern, a 10-question quiz and interview answers
A tagged union in C is a union paired with a tag that says which member is valid, and real firmware rarely uses a lone union without one. This last lecture of the structure and union chapter nests unions inside structures and structures inside unions, and this last lecture of the structure and union chapter shows how. You will build the tagged-union pattern, use the C11 anonymous union, give a 16-bit word named byte parts, and then test yourself with a quiz and embedded C interview questions. It is part of our free C programming course, written for students who want embedded C programming skills for jobs in firmware.
What You Will Learn
- A union inside a structure, and a structure inside a union
- The tagged union in C pattern that makes unions safe
- C11 anonymous unions and how to access their members
- A 10-question quiz with answers and explanations
- Eleven interview questions with model answers
Prerequisites
The previous lectures in this chapter: defining a union, accessing and initializing it, and comparing struct vs union memory. Know enum and fixed-width integer types.
How a Tagged Union in C Works
The problem with a bare union is that nothing records which member is valid. The solution is to wrap it in a structure together with a tag, typically an enum. Code that reads the value checks the tag first.
#include <stdio.h>
#include <string.h>
enum kind { K_COUNT, K_LEVEL };
struct sample {
char name[12];
enum kind kind; /* tag: says which member is live */
union {
int count;
float level;
} v;
};
static void print_sample(const struct sample *s)
{
if (s->kind == K_COUNT)
printf("%s: count=%d\n", s->name, s->v.count);
else
printf("%s: level=%.1f\n", s->name, s->v.level);
}
int main(void)
{
struct sample a, b;
strcpy(a.name, "irq_hits");
a.kind = K_COUNT;
a.v.count = 42;
strcpy(b.name, "tank");
b.kind = K_LEVEL;
b.v.level = 72.5f;
print_sample(&a);
print_sample(&b);
printf("sizeof sample = %zu\n", sizeof a);
return 0;
}
Build and run
gcc -Wall -Wextra -o tag tag.c
./tag
Expected output:
irq_hits: count=42
tank: level=72.5
sizeof sample = 20
This is the standard tagged union in C: the reading function never touches v.count unless the tag says it is valid. This single habit eliminates most union bugs.
Structure Inside a Union, and Anonymous Unions
A union member can itself be a structure. That lets you name the parts of a value while keeping the whole value available. C11 also allows an anonymous union inside a structure, so you skip the middle name.
#include <stdio.h>
#include <stdint.h>
union word16 {
uint16_t w;
struct { uint8_t lo; uint8_t hi; } b;
};
struct sample {
int kind; /* 0 = count, 1 = level */
union { /* C11 anonymous union */
int count;
float level;
};
};
int main(void)
{
union word16 x;
x.w = 0x1234;
printf("lo=0x%02X hi=0x%02X\n", x.b.lo, x.b.hi);
struct sample s = { .kind = 0, .count = 7 };
printf("count=%d\n", s.count);
s.kind = 1;
s.level = 0.5f;
printf("level=%.1f\n", s.level);
return 0;
}
gcc -std=c11 -Wall -Wextra -o nest nest.c
./nest
Expected output on a little-endian CPU:
lo=0x34 hi=0x12
count=7
level=0.5
| Pattern | Access | Benefit |
|---|---|---|
| Struct inside union | x.b.lo, x.w | Named parts plus the whole value |
| Named union in struct | s.v.count | Works in every C standard |
| Anonymous union in struct | s.count | Shorter, needs C11 |
Portability note
Which byte is lo depends on endianness. The output above is for little-endian CPUs; a big-endian CPU would swap the two values.
Common Mistakes With a Tagged Union in C
- Reading the union before checking the tag.
- Changing the tag but forgetting to write the matching member (or the reverse).
- Leaving the tag as an
intwithout validating values that came from a bus; always check the range. - Relying on a struct-in-union layout for wire formats.
- Using anonymous unions in code that must compile with a pre-C11 toolchain.
Best Practices for a Tagged Union in C
- Update the tag and the payload in one small function so they cannot drift apart.
- Switch on the tag and handle the default case explicitly.
- Prefer fixed-width integer types in the payload.
- Use
_Static_assertfor any layout that hardware or a protocol depends on.
Quiz: Test Your Knowledge of Structures and Unions
Try each question first, then open the answer. Answers assume a typical little-endian 64-bit GCC target.
Q1. What is sizeof of union { char c; int i; double d; } on a typical 64-bit system?
- 4
- 8
- 13
- 16
Show answer
Answer: B. The largest member is the 8-byte double, and 8 is also the required alignment.
Q2. A union has members int i and char c. After u.i = 0x41424344 on a little-endian CPU, what does u.c hold?
- A
- B
- C
- D
Show answer
Answer: D. The least significant byte 0x44 is stored first, and 0x44 is the character D.
Q3. Which member can be set with a plain brace initializer such as { 5 }?
- Any member
- The largest member
- The first member declared
- The last member declared
Show answer
Answer: C. Plain braces always target the first member. A designator is needed to pick another.
Q4. Which statement about the addresses of union members is true?
- Each has its own address
- All start at the same address
- Addresses increase by member size
- They are random
Show answer
Answer: B. Every member begins at offset zero.
Q5. What is sizeof of struct { uint8_t tag; union { uint8_t a; uint32_t b; } u; }?
- 5
- 6
- 8
- 9
Show answer
Answer: C. The union is 4 bytes and needs 4-byte alignment, so 3 padding bytes follow the tag.
Q6. After writing float f in a union, reading the int i member gives:
- The float rounded to an int
- The raw bit pattern of the float
- Always zero
- A compile error
Show answer
Answer: B. Reading another member reinterprets the bytes; no numeric conversion happens.
Q7. Why add a tag field next to a union?
- To make it faster
- To record which member is valid
- To reduce its size
- To allow comparison with ==
Show answer
Answer: B. The compiler does not remember the active member, so the program must.
Q8. Is union v d = { 1, 2 }; valid for a two-member union?
- Yes, sets both
- Yes, sets the last
- No, only one initializer is allowed
- Only in C++
Show answer
Answer: C. Only one member can hold a value, so excess initializers are rejected or warned about.
Q9. Which header provides the offsetof macro?
- stdio.h
- stdint.h
- stddef.h
- stdlib.h
Show answer
Answer: C. offsetof is defined in stddef.h.
Q10. Which is the portable way to convert a float to its raw bits in code that must also compile as C++?
- Union read
- Pointer cast to int
- memcpy into a uint32_t
- A macro
Show answer
Answer: C. memcpy is well defined in both languages.
Embedded C Interview Questions on Unions
1. What is the difference between a structure and a union?
A structure gives each member separate storage; a union overlays all members at the same address. Structure size is the sum of members plus padding; union size is the largest member plus alignment.
2. How does the compiler decide the size of a union?
It takes the size of the largest member and rounds it up to a multiple of the strictest alignment among the members.
3. How do you know which member of a union is valid?
You do not, unless you track it. The standard approach is a tag, usually an enum, stored next to the union in a struct.
4. Give an embedded use for a union.
Presenting a 32-bit register as four bytes, holding variant protocol messages in one buffer, or inspecting a float as raw bits.
5. Is it safe to send a union or struct over a network as raw bytes?
No. Padding, alignment and endianness differ between systems. Serialize each field explicitly with shifts and masks.
6. What happens when you read a union member other than the one last written?
The stored bytes are reinterpreted. C allows it, C++ does not, and the result depends on byte order and representation.
7. How would you detect endianness using a union?
Store a known 32-bit value, then inspect the first byte through a byte-array member. If it holds the least significant byte, the CPU is little-endian.
8. Can a union contain another union or a structure?
Yes. Nested aggregates are allowed, and C11 anonymous members make access shorter.
9. Can you compare two unions with ==?
No. Compare the active member, or compare the bytes with memcmp when you know all bytes are defined.
10. Why might a union save less memory than expected?
A tag field, padding and alignment add overhead, and if all members are about the same size there is little to share.
11. How do you shrink a padded structure?
Order members by decreasing alignment. Use packing only when a hardware or protocol layout requires it, since it can cause unaligned accesses.
Practice Challenges
- Write a tagged union with three kinds: 8-bit, 16-bit and 32-bit samples. Add a function that prints any of them.
- Build a union that views a 16-bit value as two bytes and print both on your machine. Then explain the output for a big-endian CPU.
- Create a struct with and without a union and use
sizeofto compute how much RAM 500 elements save. - Add
_Static_assertchecks so the build fails if your message layout changes size.
Key Takeaways
- A tagged union in C wraps a union in a struct with a tag, and you always check the tag first.
- A struct inside a union gives named parts of one value; a C11 anonymous union shortens access.
- Byte-level views depend on endianness; layouts depend on padding.
- A tagged union in C is a favourite interview topic because it tests memory, alignment and byte-order understanding.
Conclusion
You have finished the union half of the structure and union chapter: the syntax, the overlap, the initialization rules, the memory arithmetic and now the tagged-union pattern that makes it all safe. Review the quiz answers you missed and rebuild the examples on your own machine. Then continue the free embedded C course with the next chapter, and keep a tagged union in C as your default for variant data.
Frequently Asked Questions
What is a tagged union in C?
A tagged union is a struct that holds a union plus a separate field, the tag, that records which union member is currently valid. It is how C programmers build safe variant types.
Can a union contain a structure in C?
Yes. A union member can be a struct, which lets you name the parts of a value, such as the low and high bytes of a 16-bit word, while still sharing storage with the whole word.
What is an anonymous union?
C11 allows a union without a name inside a struct or union. Its members are accessed directly as if they belonged to the enclosing struct, for example s.count instead of s.v.count.
How do I prepare for embedded C interview questions on unions?
Practise sizeof results, explain overlap with a diagram, describe the tag pattern, and be ready to discuss endianness, alignment and why unions are not a safe wire format.
Why do interviewers ask about unions?
Unions test whether you understand memory layout, alignment and byte order, which are everyday concerns in firmware and driver work.
Is type punning with unions portable?
It is allowed in C, but byte order and layout are implementation details and C++ treats it as undefined. Use memcpy when the code must be portable.
Finish Strong: Free Embedded C Course
Revisit the earlier lectures, solve the practice challenges, then move to the next chapter of the course.
