Use a preprocessor constant to define the bitfield size (there may be a way to achieve a compile-time assertion without doing that but it doesn't immediately spring to my mind).
#define WIDGET_COUNT_BITS 5
#define WIDGET_MAX ((size_t)(1 << WIDGET_COUNT_BITS - 1))
struct widget_list {
unsigned count : WIDGET_COUNT_BITS;
};
If the array size is defined by a preprocessor constant, you can use the preprocessor to get an error message.
#define FROBNICATOR_WIDGET_COUNT 42
#if FROBNICATOR_WIDGET_COUNT > WIDGET_MAX
#error "Too many widgets in the frobnicator module"
#endif
widget_t widgets[FROBNICATOR_WIDGET_COUNT];
Otherwise, if you want a compile-time error based on a sizeof
value, a classic trick to is to build an array type, which most compilers reject if the array size is 0. See Static assert in C. C11 introduces _Static_assert
for that, but compiler support isn't widespread yet.