[cfe-dev] CLang 2.1 doesn't catch assert within if

Charles Davis cdavis at mymail.mines.edu
Fri Oct 7 22:16:01 PDT 2011


On Oct 7, 2011, at 11:02 PM, Don Quixote de la Mancha wrote:
> You NEVER EVER want to do the following:
> 
> if ( condition )
>  assert( must_be_true );
> 
> following_line();
> 
> If NDEBUG is defined as for a release or profile build, you'll get the
> following in your preprocessed code, which will be very hard to debug:
> 
> if ( condition )
>   following_line();
No it won't. It will look like this:
if ( condition )
  (void)0;

following_line();

That's because, when NDEBUG is defined, assert(3) is defined like so:

#define assert(cond) (void)0

> Even better is to make the if statement part of the assert:
> 
> assert( condition && must_be_true );
Actually, that's worse. Now if the condition is false, instead of skipping the assert, the assertion will now fail. What you really meant is:

assert( !(condition) || (must_be_true) );

Now the assert won't fail if the condition is false. If it is true, it will attempt to evaluate (must_be_true) like before. (I put it in parentheses because 'must_be_true' might be an expression like 'this && that', which won't work quite right without them.)

Chip





More information about the cfe-dev mailing list