C Reference ยท Keywords and Statements
The static_assert declaration
Reference for C static_assert: check constant conditions at compile time, optional messages in C23, typical uses with sizeof, enums and struct layout.
static_assert checks a condition while the program is compiled. If the constant expression is zero, compilation fails with your message; if it is nonzero, the declaration disappears and costs nothing at run time. Use it to document and enforce assumptions about type sizes, struct layouts, enum counts and configuration constants.
It is a keyword in C23; in C11 and C17 the keyword is _Static_assert, and <assert.h> provides the macro static_assert. C23 also makes the message optional. It can appear wherever a declaration or a statement is allowed, including at file scope and inside structs.
static_assert(sizeof(int) >= 4, "int must be at least 32 bits");
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
A failing check stops the compiler. It is shown here read-only:
static_assert(sizeof(int) == 8, "int is not 8 bytes"); /* error: static assertion failed: "int is not 8 bytes" */
Syntax
static_assert(constant-expression, string-literal); static_assert(constant-expression); /* C23 */ _Static_assert(constant-expression, string-literal); /* C11 and later */
| Part | Description |
|---|---|
constant-expression |
An integer constant expression. Zero means failure. |
string-literal |
Message shown by the compiler on failure. Optional since C23. |
Returns: nothing; no code is generated.
Errors: the condition must be a constant expression; a variable, even a const int, is rejected (use constexpr in C23 or an enum constant). A failed assertion is a compile-time error, not a warning.
Usage notes
- Zero run-time cost. Nothing remains in the compiled program, unlike
assert, which checks at run time. - Great for portability. State the size and range assumptions your code makes, so a port to another platform fails loudly at build time.
- Keeps tables in sync. Compare the length of a lookup table with an enum count, as in the first example.
- Struct layout. Verify
sizeofandoffsetoffor structs that must match a file format or hardware layout. - Message style. Describe the requirement ("buffer must hold a full line"), not the test.
- Pre-C23. The keyword spelling
_Static_assertworks in C11 and C17; include<assert.h>for the nicer name. - Placement. It can appear in block scope, file scope, and (C11) inside a struct or union declaration list.