
Two ways to write multi-statement macros
Quote:
> I've noticed that whenever I see multi-statement macros in this
> newsgroup they're usually written with a "do {...} while(0)" construct
> to transform them into a single statement. One of my colleagues asked
> a simple question that I can't answer: Why is this a better way to
> write multi-statement macros than simply enclosing the statements in
> braces without adding the "do" and "while(0)"?
The problem is that this program is not legal C:
#include <stdio.h>
#define macro(x) { if (x) puts("yes"); else puts("no"); puts("\n"); }
int main()
{
char s[100];
puts("Type some stuff > ");
if ((gets(s))[0] == 'a')
macro(1);
else
macro(0);
return 0;
}
whereas the same program with "do" and "while(0)" around the braces is
legal. The idea of using "do { ... } while(0)" is that the macro be
legal in all statement contexts and nowhere else; i.e. that it should
behave as though the macro were in fact a function.
--
Gareth Rees