macors and semicolons
alanb at sdl.mdcbbs.com
alanb at sdl.mdcbbs.com
Tue Jun 25 02:05:52 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++;
>
> 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 at 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 at sdl.mdcbbs.com Alan Braggins
My opinions etc.
More information about the Comp.std.c
mailing list