swap(x,y)

Wm E Davidsen Jr davidsen at crdos1.crd.ge.COM
Wed Aug 30 02:20:23 AEST 1989


In article <190 at titania.warwick.ac.uk>, cudcv at warwick.ac.uk (Rob McMahon) writes:

|                                                         My point is that if the
|  compiler does do anything like this, all you're doing by using deviosities
|  like `{ x ^= y; y ^= x; x ^= y; }' is confusing the compiler so that it will
|  miss these optimisations.

  You certainly have given a good example. 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. I could still do this by having a
macro for each type, but then the program will break if the type of the
base variable gets changed, say from float to double because I port it
to a machine with minimal float.

  If I had typing by example, such as the "same_as" extension somebody
showed me a year or so ago, I could say:
	{ same_as(x) temp; temp=x; x=y; y=temp; }
as you suggest, although the actual name of the variable might conflict.

  I still like the idea of a swap operator... x<=>y, but without it we
have to use macros or write the explicit and faster code you mentioned.

BTW: why doesn't gcc optimize the common x^=y^=x^=y expression ;-)
-- 
bill davidsen	(davidsen at crdos1.crd.GE.COM -or- uunet!crdgw1!crdos1!davidsen)
"The world is filled with fools. They blindly follow their so-called
'reason' in the face of the church and common sense. Any fool can see
that the world is flat!" - anon



More information about the Comp.lang.c mailing list