C _Static_assert Keyword
Example
Check a value when the program is compiled:
#define MAX_AGE 120
int main() {
_Static_assert(MAX_AGE > 0, "MAX_AGE must be more than 0"); // OK
// _Static_assert(MAX_AGE < 100, "MAX_AGE must be less than 100"); // Error
printf("%d", MAX_AGE);
return 0;
}
Definition and Usage
The _Static_assert keyword checks a condition when the program is compiled, not when it runs. If the condition is false, the compiler stops with an error and shows your message.
The condition must be something that the compiler can work out by itself, like a number, a #define value or a sizeof expression. It cannot use the value of a normal variable.
Use it to catch mistakes early, for example to check that a data type has the size your code needs. If you include <assert.h>, you can write static_assert instead of _Static_assert.
Related Pages
Read more about #define in our C Macros Tutorial.
Read more about compile-time errors in our C Errors Tutorial.