Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 135 ยท Structures and Unions

Unions

Learn C unions - members that share one block of memory, how big a union is, tagged unions with an enum and switch, anonymous unions and the rules for type punning.

A structure stores all of its members side by side: a struct with an int and a double holds both values at once. A union looks almost the same when you declare it, but works very differently: all of its members share the same memory. A union is big enough for its largest member, and at any moment it holds just one of them. Writing one member overwrites the others.

That sounds like a strange feature until you need it. Unions let one variable hold "either an integer, or a float, or a string", which is how interpreters store values, how network protocols describe messages with different layouts, and how parsers represent tokens. Combined with a small tag that records which member is active, a union becomes a tagged union, one of the most useful patterns in C. Unions are also the classic (and, in C, legitimate) way to look at the raw bytes of a value, called type punning.

Declaring a union

The syntax mirrors struct, with the keyword union:

C
union number {
    int i;
    float f;
    double d;
};

union number n;
n.i = 42;           /* now n holds an int */
n.d = 3.5;          /* now n holds a double; the int is gone */

Members are accessed with . and, through a pointer, with ->, exactly as for structs. The difference is all in the memory layout:

C Members share the same storage

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.

The struct needs 16 bytes (4 for the int, 4 of padding, 8 for the double), but the union only 8: the size of its largest member. Both members start at the same address, which the two identical %p lines prove. A union's size can also be rounded up beyond its largest member so that it meets the strictest alignment of all members; union { char text[5]; int n; } is 8 bytes, not 5.

The active member

At any time, the member you last wrote is the active member. Reading the active member gives you its value back, as you'd expect. Reading a different member is where unions get subtle, and it's covered under type punning below. In normal code, the rule is simple: read the member you wrote.

Nothing in the union itself records which member is active. That's your job, and forgetting it is the classic union bug: write a float, read an int, and you get a meaningless number. That's exactly why unions are usually wrapped together with a tag.

Initializing unions

A braced initializer without designators initializes the first member. To initialize another one, use a designated initializer (C99):

C
union number a = {7};            /* a.i = 7 */
union number b = {.d = 2.75};    /* b.d = 2.75 */
union number c = {0};            /* first member zeroed */

Tagged unions

A tagged union (also called a discriminated union or variant) is a struct containing an enum tag and a union. The tag says which union member is currently valid, and every piece of code that reads the value switches on the tag first. Here's a shape type where each kind of shape needs different data:

C A tagged union of shapes

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.

The circle's perimeter is 9.42, the rectangle's 13.00 and the triangle's 12.00. Each struct shape is 32 bytes: 8 for the tag (4 plus padding) and 24 for the union, sized by its largest member, the triangle. A struct with all six doubles as separate members would need 56 bytes.

A few habits make tagged unions safe:

  • Always set the tag and the matching member together. Designated initializers like {.kind = SHAPE_CIRCLE, .as.circle = {...}} keep them on one line.
  • Switch on the tag without a default case. With -Wall, GCC's -Wswitch warns when a switch on an enum misses one of its values. If you add SHAPE_HEXAGON later, the compiler points at every switch that needs updating. A default label would silence that help (see switch Statements).
  • Write constructor functions such as struct shape make_circle(double r) so the rest of the code never builds a shape by hand.

Anonymous unions (C11)

Naming the union member (as above) makes every access a little longer: s->as.circle.radius. C11 allows an anonymous union inside a struct, whose members are accessed as if they belonged to the struct directly. This is very common in tagged unions:

C A value type with an anonymous union

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.

It prints [42, "Oslo", 0.0025, true, null], a row of mixed values like you might read from a database or a JSON array, and each value takes 16 bytes. Dynamic languages work this way under the hood: CPython, Lua and SQLite all keep values in a tagged structure similar to this one.

Type punning: reading a different member

What happens if you write one member and read another? In C (unlike C++), reading a non-active member is allowed: the bytes of the stored value are reinterpreted as the type of the member you read. The C standard says so explicitly in a footnote since C99's corrections. This makes a union the traditional way to inspect the bit pattern of a float:

C Looking at the bits of a float

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.

1.0f is 0x3F800000: sign 0, exponent 127 (the bias for float), mantissa 0. -2.0f just flips the sign bit and bumps the exponent to 128, giving 0xC0000000. 0.15625f (which is 1.25 ร— 2โปยณ) is stored exactly as 0x3E200000, while 0.1f has an endless binary expansion and shows a mantissa of 0x4CCCCD, rounded at the last bit. That rounding is the root of the surprises you met in Floating-Point Numbers.

The rules around punning are worth knowing precisely:

  • Through a union: allowed in C. The result depends on the representation (IEEE 754 floats, byte order), so it's implementation-specific, but it isn't undefined behavior. If the bytes don't form a valid value of the new type (a trap representation), reading it is undefined; that's not a concern for unsigned integers like uint32_t.
  • Through a pointer cast: undefined. *(uint32_t *)&x breaks the strict aliasing rule, which lets the compiler assume an int * and a float * never point to the same object. Optimizers really do rely on this, so such code can break at higher optimization levels.
  • Through memcpy: always fine. Copying the bytes into a variable of the other type is defined in both C and C++, and compilers turn a small fixed-size memcpy into a single register move. When code must also compile as C++, use memcpy.

Warning: C++ does not allow union type punning: reading an inactive member is undefined behavior there, even though most compilers tolerate it. If you share headers between C and C++ (see C and C++), prefer memcpy, or C++20's std::bit_cast on the C++ side.

Byte order and unions

Punning between an integer and an array of bytes shows the machine's endianness, the order in which it stores the bytes of a multi-byte number:

C Which byte comes first?

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.

Our server (x86-64) prints 44 33 22 11: the least significant byte comes first, so it's little-endian, as are ARM processors in phones and Macs in their usual mode. Some network hardware and older processors are big-endian. Network protocols and file formats fix a byte order on purpose, which is why code that writes binary data should never just dump a union or struct to a file (see Binary Files).

When to use a union

Unions are a precise tool, not an everyday one. Good uses:

  • Variant values with a tag: tokens, AST nodes, configuration values, messages.
  • Saving memory when only one of several large members is used at a time, which matters in embedded systems or when you store millions of records.
  • Inspecting representations, such as float bits, in C code (or with memcpy for portability).

Situations where a union is the wrong choice:

  • When you need several members at the same time. That's a struct.
  • To convert between types. (int)3.7 converts a value; a union only reinterprets bytes, which is almost never what "convert" means.
  • To save a few bytes in ordinary code, where the risk of reading the wrong member outweighs the gain.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. On our 64-bit system, what is sizeof(union { char c; int i; double d; })?

    A union is as large as its largest member (the 8-byte double), rounded up to the strictest alignment, which is also 8.
  2. 2. union number n; n.i = 5; n.f = 2.0f; printf("%f", n.f); What does this print?

    The last write was to f, so f is the active member and reading it returns 2.0. The int value was overwritten.
  3. 3. In a tagged union, why is it a good idea to leave out the default case when switching on the enum tag?

    GCC's -Wswitch (part of -Wall) reports unhandled enumerators only when there is no default label, so new kinds can't be forgotten silently.
  4. 4. Which way of reading the bits of a float is undefined behavior in C?

    Accessing a float through a uint32_t pointer violates the strict aliasing rule. Union punning is allowed in C, and memcpy or unsigned char access is always fine.
  5. 5. union { uint32_t n; unsigned char b[4]; } w = {.n = 0x01020304}; On a little-endian machine, what is w.b[0]?

    Little-endian machines store the least significant byte first, so the first byte is 0x04.

Summary

  • All members of a union share the same memory, starting at the same address. The union is as big as its largest member, plus any padding for alignment.
  • Only the member you last wrote (the active member) holds a meaningful value; the union itself doesn't record which one that is.
  • A plain initializer sets the first member; use designated initializers ({.d = 2.5}) for others.
  • A tagged union pairs an enum tag with a union. Set the tag and member together, switch on the tag without default so -Wswitch catches missing cases, and use constructor functions. C11 anonymous unions shorten the member access.
  • In C, reading a different union member reinterprets the bytes (type punning). Pointer-cast punning violates strict aliasing and is undefined; memcpy is the portable choice and the only one that's also valid C++.
  • Byte-level views expose endianness, so don't write raw unions or structs to files or networks.

Next: Enumerations, where you'll learn everything about the enum types that make tags like SHAPE_CIRCLE readable.