DEV Community

Discussion on: How can you swap two variables without using a third?

Collapse
 
codevault profile image
Sergiu Mureşan • Edited

I like defining one of these macros when swapping variables in C:

#define SWAP(A, B) A ^= B ^= A ^= B
#define SWAP(A, B) A = A - (B = (A = A + B) - B)

The second one works on floating point numbers too.

Collapse
 
theoutlander profile image
Nick Karnik • Edited

That's a good one. Although it won't work in Javascript I think.

x=10;y=5;console.log(x,y);(x=(x-(y = (x=x+y)-y)));console.log(x,y)

Collapse
 
codevault profile image
Sergiu Mureşan • Edited

I think it doesn't like the double assignment on same expression. In JS you can do:

[a, b] = [b, a];

or

b = [a, a = b][0];

although less readable.

Thread Thread
 
theoutlander profile image
Nick Karnik

[] allocates new space I think so this solution won't be in constant space.