Page 59 - C-Language
P. 59
A static assertion is one that is checked at compile time, not run time. The condition must be a
constant expression, and if false will result in a compiler error. The first argument, the condition
that is checked, must be a constant expression, and the second a string literal.
Unlike assert, _Static_assert is a keyword. A convenience macro static_assert is defined in
<assert.h>.
#include <assert.h>
enum {N = 5};
_Static_assert(N == 5, "N does not equal 5");
static_assert(N > 10, "N is not greater than 10"); /* compiler error */
C99
Prior to C11, there was no direct support for static assertions. However, in C99, static assertions
could be emulated with macros that would trigger a compilation failure if the compile time condition
was false. Unlike _Static_assert, the second parameter needs to be a proper token name so that a
variable name can be created with it. If the assertion fails, the variable name is seen in the
compiler error, since that variable was used in a syntactically incorrect array declaration.
#define STATIC_MSG(msg, l) STATIC_MSG2(msg, l)
#define STATIC_MSG2(msg,l) on_line_##l##__##msg
#define STATIC_ASSERT(x, msg) extern char STATIC_MSG(msg, __LINE__) [(x)?1:-1]
enum { N = 5 };
STATIC_ASSERT(N == 5, N_must_equal_5);
STATIC_ASSERT(N > 5, N_must_be_greater_than_5); /* compile error */
Before C99, you could not declare variables at arbitrary locations in a block, so you would have to
be extremely cautious about using this macro, ensuring that it only appears where a variable
declaration would be valid.
Assertion of Unreachable Code
During development, when certain code paths must be prevented from the reach of control flow,
you may use assert(0) to indicate that such a condition is erroneous:
switch (color) {
case COLOR_RED:
case COLOR_GREEN:
case COLOR_BLUE:
break;
default:
assert(0);
}
Whenever the argument of the assert() macro evaluates false, the macro will write diagnostic
information to the standard error stream and then abort the program. This information includes the
file and line number of the assert() statement and can be very helpful in debugging. Asserts can
https://riptutorial.com/ 35

