4 ms·
build time asserts can be defined in C macros with some tricks. The error messages are slightly misleading, but when people look at the source code it is usuall
by nn3 7y ago
build time asserts can be defined in C macros with some tricks. The error messages are slightly misleading, but when people look at the source code it is usually clear what is happening.
#define ASSERT_BUILD(x) \
do { char array[(x) ? 1 : -1]; (void)array; } while(0)
static char foo[10];
ASSERT_BUILD(sizeof(foo) >= 10);
- lifthrasiir 7y ago> The error messages are slightly misleading, [...] A common strategy is to use a self-describing variable name like `static_assertion_failed`.
- ben-schaaf 7y agoThat's a great trick and all, but it falls disappointingly short of D's `static assert`: There's no guarantee it'll ever run. The trick assumes that the C compiler will evaluate the expression at compile time, but there's every chance that it just won't and will silently fail instead. char * i = malloc(1); ASSERT_BUILD(i); That just silently compiles and runs without triggering any failure. Whats worse is you can never be sure whether your assert is passing or the compiler decided not to run it.
- nudq 7y agoThat compiles because with gcc extensions or sufficiently recent standards, variable size arrays are now a thing. The compiler doesn't insist on a static array size. What about something like this: #define ASSERT_BUILD(x) extern int STATIC_ASSERT_FAILED[(x)?1:-1]