# Performing Compile-Time Assertions

5 replies to this topic

### #1john

Member

• Members
• 84 posts

Posted 08 September 2004 - 05:26 PM

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.

### #2baldurk

Senior Member

• Members
• 1057 posts

Posted 09 September 2004 - 02:39 PM

what compilers does this work on? I'm guessing it's not standard - does it only work on VC++?
baldurk
He who knows not and knows that he knows not is ignorant. Teach him.
He who knows not and knows not that he knows not is a fool. Shun him.

### #3Mihail121

Senior Member

• Members
• 1059 posts

Posted 09 September 2004 - 05:37 PM

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!

### #4anubis

Senior Member

• Members
• 2225 posts

Posted 09 September 2004 - 06:45 PM

hmm... me thinks that every compiler worth a dime will stop on this...
If Prolog is the answer, what is the question ?

### #5baldurk

Senior Member

• Members
• 1057 posts

Posted 09 September 2004 - 07:54 PM

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

:X
baldurk
He who knows not and knows that he knows not is ignorant. Teach him.
He who knows not and knows not that he knows not is a fool. Shun him.

### #6SnprBoB86

Valued Member

• Members
• 112 posts

Posted 10 September 2004 - 02:09 AM

http://www.boost.org...atic_assert.htm
Brandon Bloom
http://brandonbloom.name

#### 1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users