Performing Compile-Time Assertions

john 102 Sep 08, 2004 at 17:26

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.

5 Replies

Please log in or register to post a reply.

baldurk 101 Sep 09, 2004 at 14:39

what compilers does this work on? I’m guessing it’s not standard - does it only work on VC++?

Mihail121 102 Sep 09, 2004 at 17:37

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 101 Sep 09, 2004 at 18:45

hmm… me thinks that every compiler worth a dime will stop on this…

baldurk 101 Sep 09, 2004 at 19:54

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__.