C StructuresLesson 39Free preview
C Unions
This lesson is part of C · All levels
Summary
Union keeps several members with different types in the same memory location, so only one member is active at a time. Because of memory sharing, the size of the union is equal to the size of its largest member, not the number of all members. Union is useful for labeled data such as values that can be numbers or text, for example on heterogeneous parser and data structures.
Key points
- All union members share the same initial address, so writing one member over another.
- Sizeof(union) is equal to the size of the largest member that has been rounded to the alignment, not the total of all members.
- Access members use a dot operator like struct, and the programmer has to remember which member is active.
- Unions are often paired with flagged struct to form tagged unions.
- Union can be used to see memory representations between types, but be careful with aliasing rules.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.