5 ways to swap 2 variables

In languages like C, we have to be a bit tricky to swap 2 variables. Unlike python, where you can just do a, b = b, a … C programmers needs to know what’s actually happening under the hood.

So let’s see different tricks to do this —

  1. Traditional method: Using a third variable
temp=a;
a=b;
b=temp;

2. Without the third variable (with the help of little Mathemagic)

a=b-a;
b=b-a;
a=b+a;

3. In a nutshell

a=(a+b)-(b=a)

4. For non-zero variables

a=b/a;
b=b/a;
a=a*b;

5. Using bitwise XOR

a=a^b;
b=a^b;
a=a^b;

--

--

Obsessed with Tech & Biz; Building my SaaS startup; Does NOT dumb down the writing; Skilled Wordsmith; Delivers the best — https://links.nishu.io

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nishu Jain

Obsessed with Tech & Biz; Building my SaaS startup; Does NOT dumb down the writing; Skilled Wordsmith; Delivers the best — https://links.nishu.io