Swap Without a Temp Variable

Hey everyone! I just thought I would share this little technique, because it was unknown to me after a year of programming experience!

int a = 5, b = 6;

// swapping now:

a = a + b; 
// a = 11

b = a - b; 
// b = a + b - b
// b = a
// b = 5

a = a - b; 
// a = a + b - (a + b - b)
// a = b
// a = 6

In the code’s comments, I used substitution to prove that this method works.

You may have already known about this, but since it took me a year to find out, I thought I would expedite the process for my pals at 0x00sec!

Swap on,
oaktree

11 Likes

Very nice! How Python spoils us:

a, b = b, a 

:joy:

3 Likes

The same goes for Ruby.

This topic was automatically closed after 30 days. New replies are no longer allowed.