1

To save space in an embedded C project, I am using bit fields to index some small arrays. Because a bit field size must be a constant, this means defining two interdependant constants with the corresponding possibility for error if one or the other is independantly changed.

I am looking for a way to use the preprocessor to check if the defined bit field size is large enough to contain the array size. This should produce a compile error.

AstroCB
  • 12,337
  • 20
  • 57
  • 73
  • why don't you just define the bitfield size then just compare when needed. For example `#define BITFIELDSIZE 6` `assert(ARRAYSIZE < (1 << BITFIELDSIZE))` – phuclv Mar 15 '14 at 13:45
  • What kind of space are you saving by doing this? – EvilTeach Mar 15 '14 at 13:50

1 Answers1

2

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.

Community
  • 1
  • 1
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254