Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Potential Problem in "Swapping values of two variables without using a third variable"

Tags:

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?

like image 831
Pattrick Avatar asked Sep 18 '10 11:09

Pattrick


People also ask

How do you swap values of two variables without using the third variable?

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 do you swap two variables without using third variable in Automation Anywhere?

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.

How can I swap two strings without using a third 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.


2 Answers

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
like image 27
Component 10 Avatar answered Sep 25 '22 07:09

Component 10


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.

like image 103
Prasoon Saurav Avatar answered Sep 21 '22 07:09

Prasoon Saurav