06 July 2007

C puzzle

I was reading source code this morning and came across this curious line in a header file:

JS_STATIC_ASSERT(sizeof(JSGCThing) >= sizeof(JSString));

The effect of this macro is to check at compile time that sizeof(JSGCThing) >= sizeof(JSString). If the condition is not met, compilation fails with an error.

The puzzle is: how does this work? A hint is in the comments.

1 comment:

jto said...

Hint: The error is not generated with #error; macros can't do that, as far as I know.

Hint: How else might a macro trigger a compile-time error?

Hint: Is there any other conceivable place in a C header file where an expression is allowed, other than preprocessor directives like #if?

Answer: See for yourself -- it's implemented on line 70 of this header file:
http://lxr.mozilla.org/seamonkey/source/js/src/jsutil.h#70