[On building a "compile-time assert" macro]
In article <>
Jordan Abel <> wrote:
>An array definition with size 0 is also a compile error.
It is in Standard C. Unfortunately, GNUC is quite popular, and
arrays with size zero are fine in GNUC, so in practice one must
often come up with a trick that works in both Standard C *and* GNUC.
(Zero-size arrays are probably available in some other not-quite-C
languages as well.)
>How about
>#define CHECK(expr) (void)((int(*)[(expr)!=0])0)
>cast /* null pointer constant */ 0 into pointer to array (expr)!=0 of
>int, then cast to void, discarding.
The (expr)!=0 part converts to 0 (if expr is false) or 1 (if expr
is true), which works fine for Standard C (as noted above). To
make it work for both Standard C and not-quite-C, we can convert
1 to 1 and 0 to -1:
#define TRUE_PLUS1_FALSE_MINUS1(expr) ((((expr) != 0) * 2) - 1)
#define COMPILE_TIME_ASSERT(expr) \
(void)sizeof(char [TRUE_PLUS1_FALSE_MINUS1(expr)])
or similar.
Note that both your CHECK and my COMPILE_TIME_ASSERT have to
be put in the "code" part of a program (inside a block, and
after the declarations in C89). There is a variant that can
appear only where declarations can go:
#define COMPILE_TIME_ASSERT_WITH_NAME(expr, name) \
typedef char name[TRUE_PLUS1_FALSE_MINUS1(expr)]
which is probably most useful with a few auxiliary macros to
generate an assertion-name based on source line number:
#define CONCAT(x, y) x ## y
#define CONCAT_EXPANSION(x, y) CONCAT(x, y)
#define COMPILE_TIME_ASSERT_2(expr) \
COMPILE_TIME_ASSERT_WITH_NAME(expr, CONCAT_EXPANSION(ASSERT, __LINE__))
Of course, you can only put one COMPILE_TIME_ASSERT_2() invocation
on any logical source line ("logical" meaning "after physical lines
are joined via backslash-newline splicing"). Thus:
COMPILE_TIME_ASSERT_2(sizeof(int) == \
sizeof(long)); COMPILE_TIME_ASSERT_2(CHAR_MAX == 127);
is bad for several reasons.

--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it
http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.