F
Francois Grieu
Hi,
I'm using an assert()-like macro to test a constant expression at
compile time
#define ASSERT(condition) struct{char assert_failure[(condition)?
1:-1];}
The idea is that this macro cause a compilation error if a constant
condition
is not true (or if the condition is not constant), with some
(admitedly cryptic)
error message, e.g. "error: size of array `assert_failure' is
negative".
This works including for expression involving sizeof, and casts
(assuming the compiler is not broken and knows how to perform
arithmetic
as the target system does), for examples
struct { char this, that; } foo;
ASSERT(2 == sizeof foo); // check size of foo
#define LOW8(x) ((unsigned char)(x))
ASSERT(LOW8(0x1A5)==0xA5); // check LOW8 works
int main(void) {return 0;}
This works on several compilers, but <OT>GCC</OT> barks with a warning
on the tune of "unnamed struct/union that defines no instances".
I'm looking for a more portable alternative. Came up with
#define ASSER1(x) assert_failure_##x
#define ASSER2(x) ASSER1(x)
#define ASSERT(condition) struct ASSER2(__LINE__){char
assert_failure[(condition)?1:-1];}
which mostly works, except if ASSERT is used twice on the same line,
or worse, twice at lines with the same number in different files (this
can
occur with headers).
Anything more robust, and less heavy on namespace polution ?
TIA,
Francois Grieu
I'm using an assert()-like macro to test a constant expression at
compile time
#define ASSERT(condition) struct{char assert_failure[(condition)?
1:-1];}
The idea is that this macro cause a compilation error if a constant
condition
is not true (or if the condition is not constant), with some
(admitedly cryptic)
error message, e.g. "error: size of array `assert_failure' is
negative".
This works including for expression involving sizeof, and casts
(assuming the compiler is not broken and knows how to perform
arithmetic
as the target system does), for examples
struct { char this, that; } foo;
ASSERT(2 == sizeof foo); // check size of foo
#define LOW8(x) ((unsigned char)(x))
ASSERT(LOW8(0x1A5)==0xA5); // check LOW8 works
int main(void) {return 0;}
This works on several compilers, but <OT>GCC</OT> barks with a warning
on the tune of "unnamed struct/union that defines no instances".
I'm looking for a more portable alternative. Came up with
#define ASSER1(x) assert_failure_##x
#define ASSER2(x) ASSER1(x)
#define ASSERT(condition) struct ASSER2(__LINE__){char
assert_failure[(condition)?1:-1];}
which mostly works, except if ASSERT is used twice on the same line,
or worse, twice at lines with the same number in different files (this
can
occur with headers).
Anything more robust, and less heavy on namespace polution ?
TIA,
Francois Grieu