Member-only story
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 —
- 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;