RPGDXThe center of Indie-RPG gaming
Not logged in. [log in] [register]
 
 
Post new topic Reply to topic  
View previous topic - View next topic  
Author Message
etscrivner
Pretty, Pretty Fairy Princess


Joined: 30 Jun 2007
Posts: 9
Location: California

PostPosted: Tue Aug 07, 2007 11:12 am    Post subject: Interesting C++ Macro Concept [quote]

I was browsing around some assertion macro code the other day and I saw something strange that looked like this:

Code:

#define ASSERT(x) do { if(!(x)) { Assert::Fail(#x, __FILE__, __LINE__); } while(0)


I was wondering what the do {...}while(0) was doing around this and it was actually quite interesting and important so I thought I would share it with everyone here because I was really surprised.

It actually has to do with the fact that if you write your assert code like this (a very common way):

Code:

#define ASSERT(x) if(!(x)) { Assert::Fail(#x, __FILE__, __LINE__); }


and then write something like this:

Code:

if(b.exists())
    ASSERT(a->size() > 0);
else
    DoSomethingElse();


This evaluates to:

Code:

if(b.exists)
    if(!(a->size() > 0))
    {
        Assert::Fail(...);
    }
    else
         DoSomethingElse();


Bad stuff for sure, and definitely unintended. Thankfully though also an easy fix.

Anyway, just something to watch out for when you're coding macros, and if you want some better examples check here. Hope someone finds this helpful, or at the very least interesting :-)
Back to top  
DeveloperX
202192397


Joined: 04 May 2003
Posts: 1626
Location: Decatur, IL, USA

PostPosted: Fri Aug 10, 2007 5:37 am    Post subject: [quote]

nice tip. indeed that produces some very ugly and hard to find bugs.
_________________
Principal Software Architect
Rambling Indie Games, LLC

See my professional portfolio
Back to top  
Post new topic Reply to topic Page 1 of 1 All times are GMT
 



Display posts from previous:   
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum