What is _Static_assert keyword in C?
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_assertis available as the macrostatic_assertkeyword 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>
Syntax
The _Static_assert keyword is declared as follows:
Parameters
The _Static_assert keyword takes two arguments.
-
The expression is an
integer constant expression -
The message is a
string literal
Return value
-
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.
Examples
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