🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #3182

Re: macors and semicolons

#3182
From: alanb
Date: Mon, 24 Jun 1991 16:05
65 lines
2575 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++;
> 
> These lines of code do a simple substitution
> 
> if (spam)
>    {
>    int c;
>    c = a;
>    a = b;
>    b = c
>    };
> else
>   a++;
> 
> notice the }; on the last line of the substitution.  This means that the else
> is a syntax error!  With swap, there are a number of simple solutions...
> 
> #define SWAP(a, b) (b = (b ^ a) ^ (a = (b ^ a) ^ a))
> 
> simple hu?  but it only words with ints or longs. 
> 
> Question time....
> how do I define a swap macro that swaps two doubles, allows the ';' on the end
> of the macro call, but does not cause a systax error when used in this context?
> 
> 
> Andrew
> andrew@otago.ac.nz
> 

Use overloaded inline functions in C++
inline void swap (double &a, double &b) {double c; c = a; a = b; b = c;}
(unlikely to be an option, but (IMHO) the cleanest solution)

or
#define SWAP(a, b) do {double c;  c = a; a = b; b = c} while (false)

If you want the same macro to work with int or doubles
#define SWAP(type, a, b) do {type c;  c = a; a = b; b = c} while (false)

(And call 'c' something else unless you are sure you will never have a
macro argument that clashes with it e.g. use _m at the end of all variables
declared inside macros - makes life easier with a debugger too. But I assume
you just wanted nice short names for the illustration - reasonable.)

Some compilers will give you a warning about "while (false)". This is a good
sign - it proves they've worked out they don't need to put in any code to
implement the loop :-)

The other argument I've seen is if you use a macro, you should know about it
and not use the semi-colon. Personally I only like this argument for things
macros with unmatched braces, which couldn't be mistaken for (or replaced
with) a function.

alanb@sdl.mdcbbs.com   Alan Braggins
My opinions etc.
Technical Details
Message-ID: <1991Jun24.170552.1@sdl.mdcbbs.com>
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!sdl.mdcbbs.com!alanb
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!cs.utexas.edu!uunet!sdl.mdcbbs.com!alanb
From: alanb@sdl.mdcbbs.com
Newsgroups: comp.std.c
Subject: Re: macors and semicolons
Message-ID: <1991Jun24.170552.1@sdl.mdcbbs.com>
Date: 24 Jun 91 16:05:52 GMT
References: <1991Jun24.213932.595@otago.ac.nz>
Organization: Shape Data Ltd. (McDonnell Douglas M&E, Cambridge UK)
Lines: 65
Nntp-Posting-Host: shapeg
Nntp-Posting-User: alanb