union Unions with shared storage
union Unions with shared storage
union members share one address. Writes change the active member; other reads are restricted. Size fits the largest member plus possible tail padding.
| Category | Struct / Union / Enum |
|---|---|
| Kind | Keyword / Statement |
| C standard | C89 / C90 |
📝 Syntax
union U { int i; float f; };
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
number = 42
letter = A
shared address = 1
ℹ️ Info The example writes the active member before each use, then compares the union's address with a member's address to demonstrate shared storage without reading an inactive member. sizeof(union Value) may include tail padding and is not guaranteed to equal the largest member's size exactly.
🏷️ Related struct/union/enum
📚 Related Tutorials
❓ FAQ
QIs a union's size always equal to its largest member's size?
ANot necessarily. It must be large enough for the largest member and satisfy the union's overall alignment, so trailing padding may make sizeof return a larger value.
QCan an int be written to a union and then read directly as a float?
AThis should not be treated as numeric type conversion. Members share object representation, and reading through another member involves type-punning and representation rules, potentially including trap representations. Use ordinary assignment or an explicit cast for numeric conversion.
QHow can a program know which member a union currently holds?
AA union does not record its active member automatically. A common approach is to store an enumeration tag alongside it in an outer structure, update the tag whenever a member is written, and check it before reading.