In this blog post, you will learn the _Static_assert in C with its application. you will also learn how to stop the compiling process if the condition is not true (tests an assertion at compile time). Basically, static assertions are a way to control the compilation process. If the specified constant expression is false, the compiler displays the specified error message and stops the compiling process. If it isn’t, there’s no effect. So let’s first understand what is _Static_assert in C?
What is _Static_assert in C?
A _static_assert
is a keyword introduced in C11. It is defined in the <assert.h>
header file. This keyword is also available in form of macro static_assert
, available in the header <assert.h>.
Syntax of _Static_assert Keyword:
_Static_assert ( expression , message ) (since C11) _Static_assert ( expression ) (since C23)
Parameters
constant-expression:
The constant expression must be an integer constant expression. If the value of the constant expression is non-zero, the declaration has no effect. Otherwise, the constraint is violated and the implementation will produce a diagnostic message which should include the text of the string literal if present.
string-literal:
The message displayed if constant-expression evaluates to zero (false). The message must be made using the base character set of the compiler. The characters can’t be multibyte or wide characters.
C program to understand working of Static_assert function:
Below mentioned C example code shows the usage of Static_assert().
#include<stdio.h> #include <assert.h> enum Items { A, T, I, C, l, E, W, O, R, L, D, LENGTH }; int main() { // _Static_assert is a C11 keyword _Static_assert(LENGTH == 11, "Expected Items enum to have eleven elements"); // This will produce an error at compile time //if int size greater than 16 _Static_assert(sizeof(int) == 2, "Expecting 16 bit integers"); return 0; }
Output:
Explanation:
In my setup size of int is 4 bytes. So you can see I am getting compiler errors. The program will compile successfully on setup which has the size of int is 2 bytes.
Recommended Post:
- log2 function in C.
- Use of log10 function in C.
- log function in C.
- fabs use in C language.
- abs labs llabs functions in C/C++.
- floor function in C with example code.
- ceil function use in C programming.
- Use of pow function in C language.
- C program to calculate the power of a number.
- sqrt function in C.
- C program to find all roots of a quadratic equation using switch case.
- C program to find the roots of a quadratic equation.
- How to find whether a given number is prime number in C?
- Use of isxdigit in C programming.
- How to use ispunct function in C programming?