Bart said:
Your macro (the same as Fredericks) left me curious.
Why is there a need for do{ ... }while(0)? Isn't it
sufficient to simply use curly brackets? like
#define swap(a,b) {temp=a; a=b; b=temp;}
With this the if statement in the OPs example is
properly expanded. Maybe you have an example, where
only braces are not sufficient...
Whether braces are sufficient or not depends on how you're
going to use the macro in your code. If you use it as
some_macro(arguments)
**without** a semicolon in the end , then braces will always
be sufficient. That's the style I prefer. But some would consider
it unnatural since statements in C are terminated by semicolons.
So you might be tempted to write instead
some_macro(arguments) ;
This will work in many cases. But consider the following code snipet
if (something)
some_macro(arguments) ;
else {
some code
}
This will expanded to
if (something)
{macro statements} ;
else {
some code
}
In this case the if block gets terminated in the semicolon
which follows the macro expansion so the else will produce
an error or even worse might be considered as the else clause
of a different if than the one you intended.
On the other hand if the macro had been defined with the
do...while(0) trick then the code would be expanded to
if (something)
do {macro statements} while(0) ;
else {
some code
}
which works as intended.