Is this swap() macro correct?
brnstnd at stealth.acf.nyu.edu
brnstnd at stealth.acf.nyu.edu
Wed Jan 17 20:34:05 AEST 1990
Say swap() is defined as
#define block do {
#define endblock } while(0)
#define swap(x,y,typ) block typ *_MV_x = x; typ *_MV_y = y; typ tmp;\
tmp = *_MV_x; *_MV_x = *_MV_y; *_MV_y = tmp; endblock
Now constructions like swap(f++,g++,real) work and are faster than a
function call. Most optimizers are even smart enough to realize that the
do { } while(0) is purely syntactic.
swap() does not work within an expression, and the macro will fail
miserably if _MV_whatever is another macro. Other than that, does swap()
have any side effects or other problems? Is anyone interested in a program
that converts functions to these inline functions automatically?
(Don't bother saying ``if typ is a struct or union and your compiler
isn't ANSI then swap() will fail.'' I'm thinking about the problems
of the conversion from function to macro, not of swap() in particular.)
---Dan
More information about the Comp.lang.c
mailing list