Swap Contents of Two Variables

So, what is new about this?

We have two well known answers to this question:

a = a – b;

b = a – b;

a = a – b;


a = a ^ b;

b = a ^ b;

a = a ^ b;

Interesting to note is that the XOR version does not care about the type of the data. For example, if a and b are int and float, then the subtraction may not result in exact values, but, the XOR operation does it without a hitch.

There are other versions like keeping them in a single statement. One interesting version is this:

((a ^=b) || 1) && ((b ^=1) || 1) && ((a ^=b) || 1);

Without those 1s and ||s, it is clear that it is just a fancy way of putting the normal method. But why are those extra operators? If the result is 0, then the rest of the swap fails because of the logical and operator. So, I think this one is better:

a ^=b, b ^=a, a^=b

There was also a mention of:

a ^= b ^= a ^= b;

This, as I learn, does not work because there are two assignments to a in this line and even though the expressions are evaluated from right to left, the compiler is apparently free to choose any of the one value to update a.

This, as I again learn, has something to do with sequence points in C and C++. Need to figure that out. Man, I am learning a lot from William Wu’s forums. 🙂


One thought on “Swap Contents of Two Variables

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s