New |

New |

Home |
---|

How to SWAP values of two variables without using a third variable

Simple:

x = 10

y = 20

x = x + y

y = x - y

x = x - y

first we are adding the two numbers and keeping the result in one of the variable.

In the above example its x and it contains x+y.

In the second operation, we are deducting y from x and assigning it to y.

Now lets break the equation logically:

y = x – y => x + y – y => x // [ since x = x + y ]

Bitwise operations:

Let's try with the XOR operator.

x = x XOR y

y = x XOR y

x = x XOR y

In a single line (that will make people reading your code mad):

x ^= y ^= x ^= y

Enjoy,

Rob.