etscrivner Pretty, Pretty Fairy Princess
Joined: 30 Jun 2007 Posts: 9 Location: California
|
Posted: 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 :-)
|
|