_Static_assert / static_assert
/ STAT-ik a-SERT /
An ordinary assert() checks a condition while the program runs, and aborts if it is false. But some facts should be checked BEFORE the program runs at all — for instance, that an int is at least 4 bytes, or that a struct has the size your protocol expects. A static assertion is a check the compiler performs at compile time: if the condition is false, compilation fails with your message; if true, it produces no code at all.
You write it as static_assert(constant-expression, "message") (the keyword is _Static_assert in C11, with the friendlier name static_assert available via <assert.h>, and made a true keyword in C23 where the message is optional). The condition must be a constant expression the compiler can evaluate, such as sizeof(int) >= 4 or (FLAGS & 0x3) == 0. Because it is evaluated at compile time, there is zero runtime cost and the broken build catches the problem before any user ever runs the program.
It matters as a guardrail for assumptions that, if wrong, would cause silent corruption: structure layout for binary formats, table sizes matching enum counts, alignment requirements, and platform word sizes. The caveat to remember: the expression must be a CONSTANT expression — you cannot static_assert about a runtime value or the result of a normal function call; for runtime checks you still use assert() or your own error handling.
#include <assert.h> static_assert(sizeof(int) >= 4, "this code assumes 32-bit int"); struct packet { unsigned char a, b; unsigned short c; }; static_assert(sizeof(struct packet) == 4, "packet must be 4 bytes");
If either fact is false on the target, the build stops with the message — no broken binary ever ships.
It only works on constant expressions known at compile time; it cannot validate runtime data — for that you still need assert() or explicit error handling.