_Static_assert declaration (C11)

Note: IBM supports selected features of C11, known as C1X before its ratification. IBM will continue to develop and implement the features of this standard. The implementation of the language level is based on IBM's interpretation of the standard. Until IBM's implementation of all the C11 features is complete, including the support of a new C11 standard library, the implementation may change from release to release. IBM makes no attempt to maintain compatibility, in source, binary, or listings and other compiler interfaces, with earlier releases of IBM's implementation of the C11 features.
Static assertions can be declared to detect and diagnose common usage errors at compile time. A _Static_assert declaration takes the following form:
Read syntax diagramSkip visual syntax diagram
_Static_assert declaration syntax

>>-_Static_assert--(--constant_expression--,--string_literal---->

>--)--;--------------------------------------------------------><

The constant_expression must be an integer constant expression. If the integer constant expression evaluates to 0, the compiler issues a severe error containing the string literal with the source location of the _Static_assert declaration. Otherwise, the _Static_assert declaration has no effect.

The declaration of static assertions does not declare a new type or object, and does not imply any size or time cost at run time.

static_assert is a macro defined in assert.h for C.

The addition of static assertions to the C language has the following benefits:
  • Libraries can detect common usage errors at compile time.
  • Implementations of the C Standard Library can detect and diagnose common usage errors, improving usability.
You can declare static assertions to check important program invariants at compile time.

Examples: _Static_assert declaration

Example 1: The following example demonstrates the use of a _Static_assert declaration inside a structure.
 #include <stddef.h>
 struct __attribute__((packed)) B{
    char a;
    int i;
 };
 
 struct A{
    struct B b;
    _Static_assert(offsetof(struct B,i)==1,"S not packed");
 };
Example 2: The following example contains static assertions declared with static_assert, so the assert.h header file must be included.
 /* static_assert requires <assert.h> */
 #include <assert.h>
 static_assert(sizeof(long) >= 8, "64-bit not enabled.");
Example 3: The following example shows the use of a _Static_assert declaration with an invalid constant expression.
 _Static_assert(1 / 0, "never shows up!");
When you compile this program, the compiler does not show the string literal in the _Static_assert declaration. Instead, the compiler issues an error message indicating that the divisor cannot be zero.