int A = 10;
int B = 20;
A ^= B;
B ^= A;
A ^= B;
cout << A << " " << B;
If you are looking for an explanation....:
The XOR operator (^) has the interesting property of being self-undoable. That is:
1 2
x ^ x == 0 // for all values of x
(x ^ z) ^ x == z // for all values of x or z
This basically allows you to "merge" two numbers.
With this in mind, the code above operates like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int A = 10;
int B = 20;
// this 'merges' B into A. As a result, A==10^20
A ^= B;
// this merges the new value of A (10^20) into B
// since B already contains 20, this means B == (10^20^20).
// The XOR then cancels the 20's out, meaning B == 10
B ^= A;
// now we merge the new value of B (10) into A (10^20)
// this means A == (10^10^20)
// again, the XOR cancels out the 10's, leaving A == 20
A ^= B;
// A and B have been effectively swapped. No 3rd variable used.
@Awais Tahir, keep in mind that not using a third variable is a bad thing, it's slower to execute and harder to understand, although it makes for a nice beginner puzzle.