
- C Library - Home
- C Library - <assert.h>
- C Library - <complex.h>
- C Library - <ctype.h>
- C Library - <errno.h>
- C Library - <fenv.h>
- C Library - <float.h>
- C Library - <inttypes.h>
- C Library - <iso646.h>
- C Library - <limits.h>
- C Library - <locale.h>
- C Library - <math.h>
- C Library - <setjmp.h>
- C Library - <signal.h>
- C Library - <stdalign.h>
- C Library - <stdarg.h>
- C Library - <stdbool.h>
- C Library - <stddef.h>
- C Library - <stdio.h>
- C Library - <stdlib.h>
- C Library - <string.h>
- C Library - <tgmath.h>
- C Library - <time.h>
- C Library - <wctype.h>
- C Programming Resources
- C Programming - Tutorial
- C - Useful Resources
C Library - static_assert() macro
The C assert library static_assert() macro is a powerful tool introduced in the C11 standard that allows you to perform compile-time assertions. This means that you can check certain conditions at compile time rather than at runtime, catching potential errors early in the development process.
Syntax
Following is the C library syntax of the static_assert() macro −
static_assert (boolean_expression, message);
Parameters
This macro accepts following parameters −
boolean_expression − This is a constant expression that the compiler evaluates at compile time. If this expression evaluates to 0 (false), the compilation fails.
message − This is a string literal that provides a description of the error when the assertion fails. This message is displayed during compilation if the assertion fails.
Return Value
This macro does not return a value. Instead, it either allows the compilation to proceed if the assertion is true or causes a compile-time error if the assertion is false.
Example 1: Ensuring Size of a Data Type
This example checks if the size of int is 4 bytes. If not, the compilation fails with the message "int must be 4 bytes".
#include <assert.h> static_assert(sizeof(int) == 4, "int must be 4 bytes"); int main() { return 0; }
Output
The above code produces following result−
error: static assertion failed: "int must be 4 bytes"
Example 2: Checking Structure Alignment
In this example, we use the offsetof macro to ensure that the int b member of MyStruct is aligned to a 4-byte boundary. If not, the compilation fails.
#include <assert.h> struct MyStruct { char a; int b; }; static_assert(offsetof(struct MyStruct, b) % 4 == 0, "int b must be aligned to 4 bytes"); int main() { return 0; }
Output
After execution of above code, we get the following result
error: static assertion failed: "int b must be aligned to 4 bytes"