I found this common solution :-
int a=10, b=20;
a=a+b;
b=a-b;
a=a-b;
But what if a=2147483647 the largest value of an integer then probably a=a+b will not be feasible.
I found this common solution :-
int a=10, b=20;
a=a+b;
b=a-b;
a=a-b;
But what if a=2147483647 the largest value of an integer then probably a=a+b will not be feasible.
How about using the std libs? ;)
std::swap(a,b);
Although you may also use the XORing algorithm but dont use it until you really have to.
The reason is well explained here:-
On modern CPU architectures, the XOR technique is considerably slower than using a temporary variable to do swapping. One reason is that modern CPUs strive to execute instructions in parallel via instruction pipelines. In the XOR technique, the inputs to each operation depend on the results of the previous operation, so they must be executed in strictly sequential order. If efficiency is of tremendous concern, it is advised to test the speeds of both the XOR technique and temporary variable swapping on the target architecture.
Although its too late but since you have not mentioned that you want build in functions or not hence the swap
method is the easiest one.
However you may also try to use the XOR method(although check the above reference about its performance) like this:
a ^= b;
b ^= a;
a ^= b;
The solution is:
a ^= b;
b ^= a;
a ^= b;
It works because x ^ x
equals 0 for any value of x, and thus, x ^ y ^ x
(in any order) equals y for any values of x and y. It's unlikely to be faster than just using a temporary though (unless you're programming for a CPU with high register contention and no pipelining ability).