</>EmbeddedInterview

What is _Static_assert and why is it useful?

MediumC Programming

Short answer: _Static_assert(condition, "message") (C11; static_assert with <assert.h>, and a keyword in C23) checks a constant expression at compile time. If the condition is false, the build fails with your message. It costs nothing at run time, so it is ideal for checking assumptions about sizes, layouts and configuration that would otherwise cause subtle run-time bugs.

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

typedef struct {
    uint8_t  type;
    uint8_t  flags;
    uint16_t length;
    uint32_t crc;
} __attribute__((packed)) frame_hdr_t;

static_assert(sizeof(frame_hdr_t) == 8, "frame header must be 8 bytes on the wire");
static_assert(offsetof(frame_hdr_t, crc) == 4, "crc must be at offset 4");

#define RX_BUF_SIZE 128u
static_assert((RX_BUF_SIZE & (RX_BUF_SIZE - 1u)) == 0, "RX_BUF_SIZE must be a power of two");

static_assert(sizeof(void *) == 4, "this driver assumes a 32-bit target");

Typical uses in firmware

  • Struct sizes and offsets that must match hardware, a protocol, flash layout or a bootloader.
  • Ring-buffer sizes that must be powers of two (for & (size - 1) wrapping).
  • Lookup tables that must have one entry per enum value: static_assert(ARRAY_SIZE(state_names) == STATE_COUNT, "..."); catches a forgotten table entry when someone adds a state.
  • Timer and baud-rate calculations that must fit in a register's range.
  • Assumptions about type sizes and endianness when porting.

Compared with assert(): assert() checks at run time, costs code, and disappears with NDEBUG. static_assert can only check things known at compile time but catches them before the code ever runs.

Before C11, projects used tricks such as declaring an array with a negative size when the condition is false: typedef char check_size[(sizeof(x) == 8) ? 1 : -1];. You may still see this in older code.