Swapping integers in one line

Is there any trick to sort the integers in just a line?

1 Like

There are many ways to swap the integers. But the simplest one is mentioned below.

Simple Method:

x = x + y - (y = x);

bit twiddling method(there might be unexpected behavior in some cases!:

if (a != b) { 
   a ^= b ^= a ^= b;  \\same as a=(b=(a=b^a)^b)^a
}

Other methods:

a += b -= a = b-a;

a /= b = (a = a*b) /b;
2 Likes

@drp48603 You can use predefined swap function in c++ by including algorithm library.

For swapping two variables a and b, it can be simply used as std::swap(a,b). For more details you can see here.

x = x + y - (y = x); is the best. But it is compiler dependent.

1 Like

True(Y). But it works in c++.

Two swap two integer a and b are in python
a,b=b,a

1 Like

To swap two integers you can use a temporary varible in c++
swap(a,b)
t = a ;
a = b ;
b = t ;

//