Compile-time assertion
The enclosed patch implements a CTASSERT(condition)
macro that, at the top level of a file, causes a compiler error if the constant expression condition
evaluates to false. This is conciser than
#if !condition
#error Condition was false.
#endif
and applicable in situations that #if
cannot handle, because CTASSERT
allows any constant expressions, including, e.g., sizeof, while #if
is limited to C preprocessor conditional expansion. (Conversely, CTASSERT
can't be used with defined(...)
, so it does not subsume #if
.)
nickm suggested that it should be in src/lib/cc, so I put it there. If you think it should be in a different file, go for it.
The patch uses a couple of different mechanisms to implement it, depending on what the compiler supports:
- If C11 is available, it expands to
_Static_assert(condition, #condition)
. Obviously if you have a C11 compiler this is the best way to do it, because it is most likely to give the best error message. - If any of
__COUNTER__
, or__INCLUDE_LEVEL__
and___LINE__
, or just__LINE__
, is available, their macro values are expanded and appended to a nametor_ctassert_
which is typedef'd to an array type with negative length if the condition is false, and positive length if the condition is true. This has zero run-time overhead; the use of__COUNTER__
, &c., is to attain a unique name, which is guaranteed with__COUNTER__
, and highly likely with__INCLUDE_LEVEL__
and__LINE__
.