Obfuscated SWAP: not portable!

Norman Diamond diamond at csl.sony.co.jp
Fri Sep 8 12:32:59 AEST 1989


In article <149 at cpsolv.UUCP>, rhg at cpsolv.UUCP (Richard H. Gumpertz) writes:
>> The exchange of x and y that has been under discussion:
>>     x ^= y ^= x ^= y
>> is non-portable because it depends on right-to-left evaluation which is NOT
>> specified in the C standard.

True, though perhaps a bit too terse for some people.

In article <1400 at levels.sait.edu.au> CCDN at levels.sait.edu.au (DAVID NEWALL) writes:

>I think it is specified.  (Perhaps it depends on whose standard you follow?)
>K&R I, page 19:
>     "The line
>        nl = nw = nc = 0;
>    sets all three variables to zero.  This is not a special case, but a
>    consequence of the fact that an assignment has a value and assignments
>    associate right to left."

OK, let's try to make it perfectly clear.

    x  ^=  y  ^=  x  ^=  y
       [3]    [2]    [1]

The order of evaluation is [1], [2], [3].  But what about the operands?

[1]  middle x   =   old x    ^   old y
[2]  new y      =   old y    ^   middle x
[3]  new x      =   which x  ^   new y

If new x = middle x ^ new y, it works.  But if new x = old x ^ new y,
it doesn't work.  Neither K&R nor the pants say when the operand value
of x is fetched for assignment [3].  It could be either before or after
assignment [1] completes.

--
-- 
Norman Diamond, Sony Corporation (diamond at ws.sony.junet)
  The above opinions are inherited by your machine's init process (pid 1),
  after being disowned and orphaned.  However, if you see this at Waterloo or
  Anterior, then their administrators must have approved of these opinions.



More information about the Comp.lang.c mailing list