typestar

Compile-time assertions in C

_Static_assert checks a constant expression while compiling, so bad builds fail early.

#include <limits.h>
#include <stdint.h>

typedef struct {
    uint32_t id;
    uint32_t flags;
} Header;

_Static_assert(sizeof(Header) == 8, "Header must stay eight bytes");
_Static_assert(CHAR_BIT == 8, "this code assumes octets");
_Static_assert(sizeof(int) >= 4, "int must hold a 32-bit value");

uint32_t header_id(const Header *h) {
    return h->id;
}

How it works

  1. It takes a constant expression and a message.
  2. Layout and size assumptions are the usual subjects.
  3. There is no run-time cost at all.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
346
Tokens
76
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 46 seconds.

Type this snippet

Step 2 of 2 in Assertions, step 11 of 12 in Preprocessor & headers.

← Previous Next →