#include<iostream>
usingnamespace std;
int main()
{
int a = 6; int b = 9;
cout << "Old a="<<a<<" Old b="<<b<<endl;
a=a+b;
b=a-b;
a=a-b;
cout << "New a="<<a << " New b=" << b;
}
#include<iostream>
usingnamespace std;
int main()
{
int a = 6; int b = 9;
cout << "Old a="<<a<<" Old b="<<b<<endl;
a=b;
b=6; //lol
cout << "New a="<<a << " New b=" << b;
}
Most modern compilers can optimize away the temporary variable in the naive swap, in which case the naive swap uses the same amount of memory and the same number of registers as the XOR swap and is at least as fast, and often faster. The XOR swap is also much less readable, and can be completely opaque to anyone who isn't already familiar with the technique.
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.
i have also thought about this method,
a=a+b;
b=a-b;
a=a-b;
my classmate already did analyzed it, i was just wondering if there is another way how to swap the two numbers without using any lib. func. or using a third variable. THANKS GUYS, see ya..