swap(x,y)

Karl Heuer karl at haddock.ima.isc.com
Thu Aug 31 10:18:06 AEST 1989


In article <230 at crdos1.crd.ge.COM> davidsen at crdos1.UUCP (bill davidsen) writes:
>However, there are reasons for doing tricks such as the XOR thing.  They
>enable me to write a macro which does the swap for any type.

Only for integral types.  It won't work on float, pointer, struct, etc.

If you insist on using a single macro, I think that
	#define swap(x,y,TYPE) {TYPE _swap_tmp_=(x); (x)=(y); (y)=_swap_tmp;}
is a better bet than the XOR hack.

I think if I were proposing a *language change* to solve this problem, I
wouldn't ask for a builtin swap operator; it's too limited.  Might as well
invent something that has other applications as well, such as the displacing
assignment operator (where  x := y  stores value y in lvalue x, but the value
of the entire expression is the previous value of x rather than the new one)
or even my reverse sequential evaluation operator (where  x,,y  evaluates
first x and then y, but (unlike the comma operator) returns y as its value;
cf. `prog1' in lisp).  Then swap would be  x=y:=x  or  x=(y,,y=x)

Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint
(Followups on this last paragraph should go to comp.lang.misc, please.)



More information about the Comp.lang.c mailing list