Friday, February 12, 2010

Swapping Variables

Here is a neat way you can swap two integer variables, x and y, without using an intermediary temporary variable:
If, x = 5 and y = 7, then:

x = x + y = 12
y = x - y = 5
x = x - y = 7

So, x = 7 and y = 5.
However, I would recommend that you keep your code simple and understandable, by using a temporary variable, as follows:
If, x = 5 and y = 7, then:

temp = x = 5
x = y = 7
y = temp = 5

So, x = 7 and y = 5.

1 comment:

  1. Another way:

    x = x ^ y;
    y = x ^ y;
    x = x ^ y;

    ReplyDelete