macros and semicolons
Michael Kahl
mkahl at world.std.com
Tue Jun 25 00:47:01 AEST 1991
In article <1991Jun24.213932.595 at otago.ac.nz> andrew at otago.ac.nz writes:
>I often get pissed off with the C pre-processor. Here is one thats been
>getting up my wick for months.
>
>#define SWAP(a, b) {int c; c = a; a = b; b = c}
>
>if (spam)
> SWAP(a, b);
>else
> a++;
>
>[discusses why this doesn't work, asks how to get it to work...]
What I do in cases like this is to surround a "statement-like" macro with
do/while(0), like so:
#define SWAP(a, b) do { int c = a; a = b; b = c; } while (0)
This expansion has the right properties: it becomes a statement when a
semicolon appears after it. If your compiler is reasonable, there will
be no overhead associated with the fake "loop".
--
Michael Kahl, Symantec Corporation
mkahl at world.std.com -or- 75236.3146 at compuserve.com
Disclaimer: Keep this quiet; what my employer doesn't know won't get me fired.
More information about the Comp.std.c
mailing list