C/C++ Macro Functions: Why use a do while statement?

Yesterday a colleague of mine ask me a question I was once presented with in an interview: Why write a C/C++ with a do while and not simply an opening and closing brace?

For those of you who are not aware it is good practice to write a macro style function using a do while statement.  This contrived example should illustrate:
#define FOO(X,Y) do { x = bar(x); y = x * y; } while(0)
The reason for doing this is actually very straight forward.  Consider the following code:

if ( baz(x) )
    FOO(x,y);
else
    y = qux(y);
When expanded the code would be:
if ( baz(x) )
    do { x = bar(x); y = x * y; } while(0);
else
    y = qux(y);
If we used just an opening a closing brace.  It would look like this:
if ( baz(x) )
    { x = bar(x); y = x * y; };
else
    y = qux(y);
You may notice that this code will not compile because of the extra semi-colon after the brace.  Of course you could simply not put the semi-colon after FOO(x,y) but it make the syntax a bit awkward and inconsistent.

Comments

Popular Posts