Member-only story

Nishu Jain
Feb 18, 2022

--

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;

--

--

Nishu Jain
Nishu Jain

Written by Nishu Jain

Obsessed with Tech & Biz | SaaS startup guy | Engineer + Wordsmith | My Medium Portfolio: https://mymedium.info/@nishu-jain

No responses yet