One of the very tricky questions asked in an interview.
Swap the values of two variables like a=10
and b=15
.
Generally to swap two variables values, we need 3rd variable like:
temp=a;
a=b;
b=temp;
Now the requirement is, swap values of two variables without using 3rd variable.
Stupid questions deserve appropriate answers:
The only good use of the
register
keyword.The best answer would be to use XOR and to use it in one line would be cool.
x,y are variables and the comma between them introduces the sequence points so it does not become compiler dependent. Cheers!
Maybe off topic, but if you know what you are swapping a single variable between two different values, you may be able to do array logic. Each time this line of code is run, it will swap the value between 1 and 2.
Using the xor swap algorithm
Why the test?
The test is to ensure that x and y have different memory locations (rather than different values). This is because
(p xor p) = 0
and if both x and y share the same memory location, when one is set to 0, both are set to 0. When both *x and *y are 0, all other xor operations on *x and *y will equal 0 (as they are the same), which means that the function will set both *x and *y set to 0.If they have the same values but not the same memory location, everything works as expected
Should this be used?
In general cases, no. The compiler will optimize away the temporary variable and given that swapping is a common procedure it should output the optimum machine code for your platform.
Take for example this quick test program written in C.
Compiled using:
The xor version takes
Where as the version with the temporary variable takes:
the general form is:
however you have to potentially watch out for overflows and also not all operations have an inverse that is well defined for all values that the operation is defined. e.g. * and / work until A or B is 0
xor is particularly pleasing as it is defined for all ints and is its own inverse