_Static_assert C11 compile-time assertions
_Static_assert C11 compile-time assertions
_Static_assert checks an integer constant expression; zero fails with a message. Runtime values such as variables and function results are invalid in it.
| Category | C11 features |
|---|---|
| Kind | Keyword / Statement |
| C standard | C11 |
📝 Syntax
_Static_assert(sizeof(int) >= 4, "int too small");
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
int width assertion passed
ℹ️ Info The assertion uses sizeof(int) * CHAR_BIT >= 32, avoiding the assumption that a C byte is always 8 bits. It compiles for GCC 10.2's 32-bit int target and prints the success message. The expression checks total width, not value bits after excluding sign and padding bits.
🏷️ Related C11 features
📚 Related Tutorials
❓ FAQ
QDoes _Static_assert check its condition while the program runs?
ANo. It checks an integer constant expression during translation. If the condition is false, the translation unit fails to compile, so no corresponding runtime check exists in a generated program.
QWhy is CHAR_BIT needed when checking int's bit width?
Asizeof(int) is measured in C bytes, and CHAR_BIT gives the number of bits in one byte. Their product is the total bit width in that implementation; a byte cannot be assumed always to contain 8 bits.
QHow should I choose between _Static_assert and assert from assert.h?
AUse _Static_assert for compile-time facts such as type sizes and constant configuration, and assert for runtime conditions such as function inputs and program state. assert may also be affected by NDEBUG, whereas static assertions are not.