What is the most elegant way to check certain conditions at compile
time? I.e. I want a compile time error to be generated if for example
the size of a struct is not a multiple of 4 or if one struct is larger
than another struct, etc.
I think of something like
#define CHECK(expr) static int dummy[((expr) != 0) - 1]
CHECK(sizeof(st ruct foo) % 4 == 0);
CHECK(sizeof(st ruct foo) <= sizeof(struct bar));
The macro expands to an array definition with size -1 which causes a
compile error, if the expr is false, i.e. zero.
The unpleasant thing in this definition is that it pollutes the names
space with a file scope name and I can use it only once per file,
since otherwise the array is defined multiply. Second, using the
preprocessor #error with an appropriate message would be nicer, but
the preprocessor #if can't be used, since the preprocessor can't
evaluate the sizeof operator.
So, is there some other nice way to achieve what I am looking for?
urs
time? I.e. I want a compile time error to be generated if for example
the size of a struct is not a multiple of 4 or if one struct is larger
than another struct, etc.
I think of something like
#define CHECK(expr) static int dummy[((expr) != 0) - 1]
CHECK(sizeof(st ruct foo) % 4 == 0);
CHECK(sizeof(st ruct foo) <= sizeof(struct bar));
The macro expands to an array definition with size -1 which causes a
compile error, if the expr is false, i.e. zero.
The unpleasant thing in this definition is that it pollutes the names
space with a file scope name and I can use it only once per file,
since otherwise the array is defined multiply. Second, using the
preprocessor #error with an appropriate message would be nicer, but
the preprocessor #if can't be used, since the preprocessor can't
evaluate the sizeof operator.
So, is there some other nice way to achieve what I am looking for?
urs
Comment