c programming tips and tricks

Swapping Two Variables without Any Temp Variable

There are three ways to do this which I’ve mentioned below.

To swap two variables without using additional space or arithmetic operators, you can simply use the xor operator.

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

// OR

a = a + b –(b=a);

// OR

a ^= b ^= a ^= b;

Leave a Reply

Your email address will not be published. Required fields are marked *