</>EmbeddedInterview

What is the difference between a structure and a union?

EasyC Programming

Short answer: In a struct, every member has its own storage, so all members hold values at the same time and the size is at least the sum of the members (plus padding). In a union, all members share the same storage; the size is that of the largest member (plus padding), and only the member last written holds a meaningful value.

struct s { uint8_t a; uint32_t b; };   /* 8 bytes on 32-bit Arm: a, 3 padding, b */
union  u { uint8_t a; uint32_t b; };   /* 4 bytes: a and b overlap */

Uses of unions

  1. Variant types (tagged unions): one value that can be one of several types, with an enum saying which.
typedef enum { MSG_TEMP, MSG_ACCEL } msg_type_t;
typedef struct {
    msg_type_t type;
    union {
        int16_t temp_c10;                 /* used when type == MSG_TEMP */
        struct { int16_t x, y, z; } acc;  /* used when type == MSG_ACCEL */
    } u;
} msg_t;                                  /* size of the largest variant, not the sum */
  1. Saving RAM when different data is never needed at the same time.

  2. Viewing the same bytes differently (type punning):

typedef union {
    uint32_t word;
    uint8_t  byte[4];
    float    f;
} reg32_t;

Type punning rules: in C (C99 TC3 onward) reading a different member than the one written is allowed and reinterprets the bytes. In C++ it is undefined behaviour (use memcpy or std::bit_cast). The byte order you see in byte[] depends on endianness, and the result is not portable between little- and big-endian systems.

Do not use unions or structs to map network or file formats directly unless you control padding, packing and endianness; serialise field by field instead.