🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #3177

Re: macros and semicolons

#3177
From: Michael Kahl
Date: Mon, 24 Jun 1991 14:47
25 lines
1308 bytes
In article <1991Jun24.213932.595@otago.ac.nz> andrew@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@world.std.com  -or-  75236.3146@compuserve.com
Disclaimer:  Keep this quiet; what my employer doesn't know won't get me fired.
Technical Details
Message-ID: <1991Jun24.144701.8479@world.std.com>
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!elroy.jpl.nasa.gov!decwrl!world!mkahl
References: <1991Jun24.213932.595@otago.ac.nz>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!elroy.jpl.nasa.gov!decwrl!world!mkahl
From: mkahl@world.std.com (Michael Kahl)
Newsgroups: comp.std.c
Subject: Re: macros and semicolons
Message-ID: <1991Jun24.144701.8479@world.std.com>
Date: 24 Jun 91 14:47:01 GMT
References: <1991Jun24.213932.595@otago.ac.nz>
Followup-To: comp.lang.c
Organization: The World @ Software Tool & Die
Lines: 25