How about a compile time statement as follows? (Yes, there are more complex CT_ASSERT macros, this illustrates the idea.)
#define CT_ASSERT(expr, name) typedef char name[(expr)?1:-1] enum { ID_DOG = 0, ID_SPIDER, ID_WORM, ID_COUNT }; int const NumberOfEyes[] = { 2, 8, 0 }; CT_ASSERT (sizeof NumberOfEyes/sizeof *NumberOfEyes == ID_COUNT, foo);
Now that the NumberOfEyes
array has more or less elements than ID_COUNT
, it will ID_COUNT
an error along xc:15: error: size of array 'foo' is negative
. Negative array sizes are a constraint violation that must be diagnosed with any C compiler.
Jens source share