swap(x,y)
Harish Hiriyannaiah
harish at csl.ncsu.edu
Tue Aug 29 00:21:11 AEST 1989
I have been reading the swap() discussion with interest, but I am still
unconvinced about the XOR trick. Let's review both of them.
[1]
temp = x;
x = y;
y = temp;
[2]
x ^= y;
y ^= x;
x ^= y;
Advantages of [2]:
(1) Works for any fundamental data type. (char, int, float etc);
(2) Does not need allocation for temp.
Advantage (1) is of more value than (2). In terms of speed, both are just
about the same.(assuming that x and y are out in memory - BTW, are there
any processors which implement XCHG for memory too, in addition to
registers ?) The allocation for temp on the stack ( assuming a stack
model ) is negligible in terms of allocation time. But in terms of
readability of the code, [2] fails over [1], unless it is properly
documented, which most people fail to do.
harish pu. hi. harish at ecelet.ncsu.edu
harish at ecebucolix.ncsu.edu
More information about the Comp.lang.c
mailing list