Skip to content
systemcoding.dev
Toolchains

Check assumptions at compile time with static_assert

Fail the build when a platform assumption is false using static_assert with a message in C11, for type sizes, CHAR_BIT and enum counts.

1 min read
Summarize in AI

Code often rests on facts about the platform, such as int being 32 bits or a table having one entry per enum value. _Static_assert, spelt static_assert through <assert.h>, turns each of those into a compile error with your own message. The struct-layout version of this is a separate snippet; this one is for the assumptions around it.

assumptions.cc
#include <assert.h>
#include <limits.h>
#include <stdint.h>

enum color { RED, GREEN, BLUE, COLOR_COUNT };

static const char *const names[] = { "red", "green" };

static_assert(CHAR_BIT == 8, "this code needs 8-bit bytes");
static_assert(sizeof(int) >= 4, "int must hold 32 bits");
static_assert(sizeof names / sizeof names[0] == COLOR_COUNT,
              "names[] is out of step with enum color");

int main(void) { return 0; }
Text
assumptions.c:12:1: error: static assertion failed: "names[] is out of step with enum color"

The message above is what GCC 14 prints in C11 mode, pointing at the line. The condition must be an integer constant expression, so it can use sizeof, offsetof and macros but not function calls. In C23 the message became optional, and static_assert is a keyword so no header is needed, as the ISO C draft N3220 specifies.

The table check is the one that pays off: add a colour and forget its name, and the build stops instead of printing a null pointer later.

Taggedc
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.