An assertion statement that is verified at the compilation time. A feature of C++11/C++14, supported by gcc since 4.3
Static assertion is written like
static_assert ( sizeof(int) >= 2 , "16 bit architecture not supported" ) ;
where the first parameter must be a constant expression, which should be possible to be evaluated at compile time. If the first expression is false
, compiler raises an error with the message given in Second parameter. If expression is true
compilation proceeds normally, without causing any impact to generated code.
Static assert was proposed because of forms of assertion are sufficient when working with templates. In GCC, supported since the version 4.3.
Earlier to static_assert
, two forms were available to raise compile time errors:
#error
pragma directive, which is not supported by all compilers. Either way, pre-processing is too early and hence not much usable.- Using tricks to prepare macros, so that compiler would raise errors. A compile time divide-by-zero, duplicated
case
in switch, zero or negative sized array were common to build compile time errors.
static_assert
is also quite used in template based programming, where to class designer expects type of arguments to be of given size and types (for example, number of bits must be less than 64 for a Bit class).
A static_assert
statement can be placed almost everywhere: globally, local to a function, in class declaration/definition, in class template etc. Thus making it highly useful.