The _Static_assert
is a keyword defined in the C11 version of C. It evaluates a constant expression at compile-time and compares the result with 0.
The
_Static_assert
is available as the macrostatic_assert
keyword defined in C11. Click here for more information onstatic_assert.
To use the _Static_assert
keyword, we need to import the assert.h
header file, as shown below:
#include <assert.h>
The _Static_assert
keyword is declared as follows:
The _Static_assert
keyword takes two arguments.
The expression is an integer constant expression
The message is a string literal
If the expression equals zero (false), the compiler generates an error and displays the second parameter.
If the expression is not equal to zero (true), there is no effect on the program.
The following code shows the use of _Static_assert
. The expression evaluates to true. Hence, the code executes successfully, and there is no effect on the program:
#include <stdio.h>#include <assert.h>int main(){//Expression evaluated to True_Static_assert (1+1 == 2, "True!");return 0;}
In the following example, the expression evaluates to false. Hence, the message in the second parameter is displayed, and the compiler generates an error:
#include <stdio.h>#include <assert.h>int main(){//Expression evaluated to False_Static_assert (1+3 <= 2, "False!");return 0;}
Free Resources