Monday, September 22, 2008

Preprocessor defines

Ok, so say you wrap your assert handler inside this:

#define ASSERT( condition ) if( g_bEnableAsserts) { \ ShowDialogBox( #condition ); Break(); }

Then you use it in your code:

void MyFunction( int n, int m )
{
ASSERT( n >= 0 )
ASSERT( m <>}


Notice the missing semicolon on the first assert? This will compile just fine, since if you expand the macro, it's a valid syntax. However, it makes it not look nice, and may cause confusion.

To fix this:

#define ASSERT( condition ) do{ if( g_bEnableAsserts) { \ ShowDialogBox( #condition ); Break(); } } while( 0 )


It doesn't look as nice, but the compile will now ask you to add the semicolon at the end.

No comments: