Originally posted by: RoyHu
Introduction
IBM XL C/C++ support the static assertion feature starting from V12.1. You can declare assertions to detect and diagnose common usage errors at compile time. To enable this feature, specify the -qlanglvl=extc1x option.
A static assertion can be declared using the _Static_assert keyword with the syntax as follows:
_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.
Benefit
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.
Example
The following example shows 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");
};
Related Reference
For details about the static assertions, see the following topic:
http://pic.dhe.ibm.com/infocenter/comphelp/v121v141/topic/com.ibm.xlcpp121.aix.doc/language_ref/sadecc1x.html
For details about the -qlanglvl=extc1x option, see the following topic:
http://pic.dhe.ibm.com/infocenter/comphelp/v121v141/topic/com.ibm.xlcpp121.aix.doc/compiler_ref/opt_langlvl.html