-3

I want to know that is there any other way of swapping 2 numbers in one line and of course without 3rd variable.

I know one way of doing this:

b=a+b-(a=b) 

or

a=a+b-(b=a)

both are same(approximately). If you know then please help me out.

verbose
  • 7,827
  • 1
  • 25
  • 40
Shaswat
  • 83
  • 1
  • 1
  • 4

2 Answers2

12

The frequently cited classic answer that you are probably looking for is:

a^=b^=a^=b;

But, it is technically wrong, because it changes the same variable more than once before a sequence point.

abelenky
  • 63,815
  • 23
  • 109
  • 159
-1

Use bit twiddling in C. Following swap two variables:

if (a != b) { 
   a ^= b ^= a ^= b;
}
Manoj Awasthi
  • 3,460
  • 2
  • 22
  • 26