What\'s the best way to achieve compile time static asserts in C (not C++), with particular emphasis on GCC?
I would NOT recommend using the solution using a typedef
:
#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(COND)?1:-1]
The array declaration with typedef
keyword is NOT guaranteed to be evaluated at compile time. For example, the following code in block scope will compile:
int invalid_value = 0;
STATIC_ASSERT(invalid_value, this_should_fail_at_compile_time_but_will_not);
I would recommend this instead (on C99):
#define STATIC_ASSERT(COND,MSG) static int static_assertion_##MSG[(COND)?1:-1]
Because of the static
keyword, the array will be defined at compile time. Note that this assert will only work with COND
which are evaluated at compile time. It will not work with (i.e. the compile will fail) with conditions that are based on values in memory, such as values assigned to variables.