I recently came along this method for swapping the values of two variables without using a third variable.
a^=b^=a^=b
But when I tried the above code on different compilers, I got different results, some gave correct results, some didn't.
Is anything terribly wrong with the code?
Example: Suppose, there are two numbers 25 and 23. X= 25 (First number), Y= 23 (second number) Swapping Logic: X = X + Y = 25 +23 = 48 Y = X - Y = 48 - 23 = 25 X = X -Y = 48 - 25 = 23 and the numbers are swapped as X =23 and Y =25.
How to swap variables without using 3rd variable? RiyaLanjewar likes this. Use the prompt-assignment variable and assign the 1st variable to it, then assign the 2nd variable to the 1st, then now assign the prompt-assignment variable which contains the 1st variable value to the 2nd variable.
Method: In order to swap two string variables without using any temporary or third variable, the idea is to use string concatenation and substring() methods to perform this operation.
If you're using C++, why not use the swap algorithm in STL? It is ideal for this purpose and it's very clear what it does:
#include <algorithm>
using namespace std;
// ...
int x=5, y=10; // x:5 y:10
swap(x,y); // x:10 y:5
Is anything terribly wrong with the code?
Yes!
a^=b^=a^=b in fact invokes Undefined Behaviour in C and in C++ because you are trying to change the value of a more than once between two sequence points.
Try writing (although not foolproof )
a ^= b;
b ^= a;
a ^= b;
instead of a^=b^=a^=b.
P.S : Never try to swap the values of two variables without using a third one. Always use a third variable.
EDIT :
As @caf noticed b^=a^=b is fine even though the order of evaluation of arguments of ^= operator is unspecified, since all the accesses of b within the expression are being used to compute the final value that is being stored in b, the behaviour is well defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With