# Thread: Swaping the variables

1. ## Swaping the variables

Hello Everyone,

I found the code for swaping two variables without using a temproray variable. this says if a and b are two variables to swap then we should do something like this--

a^=b^= ^=a ^=b;

can anyone tell me what does this statment mean? How does this statment work????

I would appreciate any help.......

2. Look here.

3. When reading the article that grumpy linked to, take special note of the last line of the "code example" section, and also carefully read the "reasons" sections.

4. Thanks for reply Gud site

5. Except the correct expression is

a^=b^=a^=b;

I wonder if this technique works for floats/doubles (well it does, at the bit-level). That is, the compiler may whine that boolean operations are a no-no. This is left as an exercise for the reader.

6. >Except the correct expression is
...not what you posted. The "correct" version of this useless and error-prone trick is:
Code:
`a ^= b, b ^= a, a ^= b;`
Note the introduction of a sequence point with each comma operator. Semicolons work as well.

7. Originally Posted by nonoob
Except the correct expression is

a^=b^=a^=b;

I wonder if this technique works for floats/doubles (well it does, at the bit-level). That is, the compiler may whine that boolean operations are a no-no. This is left as an exercise for the reader.
The compiler almost certainly will not do XOR on floating point data types, or for that matter any other non-integer type [which is not, in my nomenclature, a boolean, but a bitwise operation]. And even if you manage to convince the compiler to perform the operation itself, it is LIKELY that any modern processor will do it fairly slowly, because you would be switching between using the floating point unit and the integer unit, which means stalls on both of those units, and most likely more extra operations than the traditional temp variable swap [and modern compilers can quite often turn the temp variable into a register anyways].

[Yes, before anyone says so: SSE has a XORP/SD/S instruction that will do bitwise XOR on floating point values - but convincing the compiler to generate that instruction without half a dozen other instructions that take away the entire benefit is can be quite hard to achieve, and it is unlikely that it will actually provide better code than the most obvious temp based solution anyways].

--
Mats

8. I fear you may be right. I was experimenting with calculating an approximate square-root using masks and shifts by casting doubles to __int64 (pick you own flavour depending on compiler), and I got hideous blow-ups assigning the result. Probably because the numbers were still in the floating point unit and intermediate results were NAN or worse. Thanks for the explanation. I'll need to be much more careful in future. It seems this illustrates how the semantics of C are at odds with the underlying hardware.

Popular pages Recent additions