john at September 8th, 2004 13:26 — #1
Have you ever wanted to do compile-time checks on constant-expressions? Well, one way is to use the known method assert(expr). However, this type of check is performed at run-time. Sometimes, compile-time checks is needed, which is what this code will do:
// C_ASSERT() can be used to perform many compile-time assertions:
// type sizes, field offsets, etc.
// An assertion failure results in error C2118: negative subscript.
#define C_ASSERT(e) typedef char __C_ASSERT__[(e)?1:-1]
You might ask: How the hell does it work? Well, as the comments explain, it works by using a negative subscript (-1) in an array when the expressions to check for is false, which is of course invalid and will cause a compilation error, otherwise, if the expression is true, a positive subscript is used, which is alright. It does this by declaring (but not creating) an array with the size as the subscript.
Hope someone finds it useful.
baldurk at September 9th, 2004 10:39 — #2
what compilers does this work on? I'm guessing it's not standard - does it only work on VC++?
mihail121 at September 9th, 2004 13:37 — #3
Agreed with Baldurk here, this trick is more than dangerous and will only work on a compiler or 2. Although the most compilers (Java, etc.) nowdays do it, it's not compiler's responsibility to keep the user safe from himself!
anubis at September 9th, 2004 14:45 — #4
hmm... me thinks that every compiler worth a dime will stop on this...
baldurk at September 9th, 2004 15:54 — #5
Whoops. Maybe I should look at the code before actually commenting. For some reason I thought it was calling __C_ASSERT__, not declaring an array called __C_ASSERT__.
snprbob86 at September 9th, 2004 22:09 — #6