liveBook · Manning

Union type

As explained in Modern C, Third Edition

A C union is a user-defined type whose members occupy overlapping storage and are represented by the same memory location.

A union is a user-defined type whose members overlay one object representation instead of forming a larger object. Each member offers a different type interpretation of the same storage. section 12.2

Inspecting an unsigned value byte by byte

Define a union containing an unsigned value and an unsigned-char array sized with sizeof(unsigned). Initialize val to 0xAABBCCDD, then print val and each bytes element. One observed machine prints DD, CC, BB, AA: the low-order representation digit appears first. This byte order is implementation-defined, not normalized by the C standard. section 12.2

typedef union unsignedInspect unsignedInspect;
union unsignedInspect {
  unsigned val;
  unsigned char bytes[sizeof(unsigned)];
};
unsignedInspect twofold = { .val = 0xAABBCCDD, };

Use the union declaration and initializer to inspect the same unsigned object's value view and byte-array view. section 12.2

TAKEAWAY: unions overlay different object types over the same object representation. Viewing an object through unsigned char exposes its representation bytes, but their ordering depends on the implementation. section 12.8 section 12.2

How Modern C, Third Edition covers it

How deep it goes
Explains storage overlay, representation digits, sizeof sizing, and implementation-defined byte order, but stops short of broader union operations.
Examples
Uses an unsigned value initialized to 0xAABBCCDD and prints its overlaid bytes to reveal machine byte order.
What you can do after
Evaluate object representations and investigate implementation-defined byte order with a union and unsigned-char array.
How it connects
Connects unions with object representation, unsigned char, sizeof, CHAR_BIT, endianness, and memory alignment.

Also explained in

Compare how 10 books explain union type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.