C Reference ยท Keywords and Statements
The union keyword
Reference for C union: members that share storage, size and alignment, the active member, type punning rules and tagged unions.
A union looks like a struct, but all its members share the same storage. The union is as large as its largest member (plus any padding), and writing one member overwrites the bytes of the others. It is useful for variants that can hold one of several types at a time, and for looking at the same bytes in two ways.
Only one member holds a meaningful value at a time, the one you last stored. Reading a different member reinterprets the bytes. C allows that (unlike C++), but the result may be a trap representation or an implementation-specific value.
union number { int i; float f; };
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
union tag { member-declarations }; union tag object = {first-member-value}; union tag object = {.other = value};
| Part | Description |
|---|---|
tag |
Optional name; the type is union tag. |
| members | Declared like struct members; bit-fields are allowed, flexible array members are not. |
| initializer | A brace list without a designator initializes the first member; a designator picks another. |
Returns: sizeof is at least the size of the largest member and a multiple of the strictest alignment.
Undefined behavior: reading a member whose bytes form a trap representation for that type. Reading a different member than the last written one is permitted by C (type punning) but the value is implementation-defined; memcpy into an object of the other type is the portable alternative.
Usage notes
- No built-in tag. The union does not remember the active member. Keep the discriminator yourself, as in the tagged-union example.
- Type punning is legal in C through a union, but not in C++. Byte order (endianness) decides what the bytes mean.
- Struct vs union. A struct stores all members; a union stores one. Memory saved is the point.
- Anonymous unions inside a struct (C11) let you write
v.iinstead ofv.u.i. - Common initial sequence. If several structs in a union begin with the same members, you may read that shared prefix through any of them.
- Size and padding. Add a char array member to force a minimum size if you need a fixed-width buffer.
- Comparison.
==does not work on unions; compare members (and the tag) explicitly.
Related
struct,enum,sizeof, endianness, undefined behavior- Lessons: Unions, Padding and alignment