-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,589
  • 1
  • 24
  • 39
Shaswat
  • 73
  • 1
  • 1
  • 4

2 Answers2

10

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
  • 61,055
  • 22
  • 102
  • 154
-1

Use bit twiddling in C. Following swap two variables:

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