Structures, Unions and Enums

Article · 3:00

Grouping values into a type, the padding the compiler inserts, and the two relatives of struct.

A struct groups values of different types under one name. Members are reached with . on a value and -> on a pointer - and p->x is exactly (*p).x, which is the whole of the difference.

What surprises people is padding. The compiler inserts unused bytes so each member lands on an address that suits its type, because an unaligned read is slower or, on some processors, a fault. So a struct of char, int, char is usually twelve bytes rather than six, and reordering the members largest-first can shrink it to eight. sizeof tells you the truth; never assume it is the sum of the members, and never write a struct to a file as raw bytes expecting another machine to read it back.

A self-referential struct contains a pointer to its own type, which is how linked lists and trees exist. It must be a pointer - a struct cannot contain itself by value, because its size would be infinite.

A union stores one of several members in the same bytes, so its size is that of its largest member and writing one member overwrites the others. It is the tool for a value that is exactly one of several types, usually with an enum tag beside it saying which. Reading a member you did not write is undefined behaviour in principle and a common trick in practice.

An enum is a named set of integer constants, and typedef gives a type a shorter name so you can write Point rather than struct Point.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>

/* Padding: the compiler aligns each member, so this is NOT 6 bytes. */
struct Wasteful { char a; int b; char c; };        /* usually 12 */
struct Packed   { int b; char a; char c; };        /* usually 8  */

typedef enum { SHAPE_CIRCLE, SHAPE_RECT } ShapeKind;

/* A tagged union: the enum says which member is the live one. */
typedef struct {
    ShapeKind kind;
    union {
        struct { double radius; }          circle;
        struct { double width, height; }   rect;
    } as;                 /* one set of bytes, shared */
} Shape;

/* Self-referential: the member must be a POINTER, or the type would
   have infinite size. */
typedef struct Node {
    int value;
    struct Node *next;
} Node;

int main(void)
{
    printf("Wasteful %zu, Packed %zu\n",
           sizeof(struct Wasteful), sizeof(struct Packed));
    printf("offset of b in Wasteful: %zu\n", offsetof(struct Wasteful, b));

    Shape s = { .kind = SHAPE_RECT, .as.rect = { 3.0, 4.0 } };

    switch (s.kind) {
    case SHAPE_CIRCLE: printf("area %f\n", 3.14159 * s.as.circle.radius
                                                   * s.as.circle.radius); break;
    case SHAPE_RECT:   printf("area %f\n", s.as.rect.width
                                         * s.as.rect.height); break;
    }

    Node second = { 2, NULL };
    Node first  = { 1, &second };

    /* p->x is exactly (*p).x. That is the entire difference. */
    for (Node *it = &first; it != NULL; it = it->next)
        printf("%d ", it->value);
    printf("\n");

    printf("union is %zu bytes - its largest member, not the sum\n",
           sizeof s.as);
    return 0;
}