# Why ^ will swap values?

Show 80 post(s) from this thread on one page
Page 2 of 2 First 12
• 04-21-2002
Prelude
>Why? Any side effects?

a ^= b ^= a ^= b;

Notice that a is changed more than once between sequence points, which makes the entire expression undefined. It's similar to a[x] = ++x;.

But assuming that you declare it properly, like so:

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

This is valid C code, but it doesn't work for general data types, or even all possible values of the data types it appears to work for. Conclusion? Avoid swap hacks like this because they are too dangerous for real programs.

-Prelude
• 04-23-2002
drharv
Hey all,

Just wondering if it is also bad to use the following:

a += b;
a -= b = a - b;

Our teacher asked us how to switch two variables without using any others, and said this answer was "simple minded" when I gave it and not the xor version.

Is this really much worse (if any), besides the fact that it takes all of two to three more keystrokes.

P.S. Please don't flame me too bad if this really is worse than the other. My ego can't take much more, lol.
• 04-23-2002
Salem
> Just wondering if it is also bad to use the following:
Yes

> Our teacher asked us how to switch two variables without using any others
Wonder if you will learn anything useful, as opposed to a bunch of silly tricks

Swapping variables without temporaries ceased to be of any use when we left assembler and started using C.

Code:

```#include <stdio.h> void s1 ( int a, int b ) {     a ^= b;     b ^= a;     a ^= b;     printf( "%d %d\n", a, b ); } void s2 ( int a, int b ) {     int temp = a;     a = b;     b = temp;     printf( "%d %d\n", a, b ); } int main ( ) {     s1( 1, 2 );     s2( 1, 2 );     return 0; }```
Guess which one is more efficient when you compile this?
gcc -S prog.c

Guess which one is more efficient when you turn on the optimiser?
gcc -S -O prog.c

In both cases, the results are in prog.s

User's of GUI front end compilers will have to RTM to find out.

Guess which one is clearer in it's intent to the average reader?

Guess which one will work with types other than int?

> Is this really much worse (if any),
You might be relying on unspecified overflow and underflow properties of integers
• 04-23-2002
drharv
I tried the commands you suggested and that is very interesting. A very good lesson that less code does not always equal better code. Thanks.
• 04-24-2002
Magos
Quote:

Originally posted by Shiro
If I am correct it only applies to integer values and not to floating point values.
How come? All variables are represented as a serie of 1's and 0's. Shouldn't be any difference if 10101011 is an int or a float... I think...
• 04-24-2002
Salem
> How come?
Easy, just define two floats, and try and use the ^ operator
Show 80 post(s) from this thread on one page
Page 2 of 2 First 12