2009-07-31

Swap two variable values

That’s the typical example when we’re all learning how to code, swap the values of a and b. Well, here’s what they probably taught us:

  1: int a = 4;
  2: int b = 3;
  3: int temp;
  4: //Swap
  5: temp = a;
  6: a = b;
  7: b = temp;

And here’s the way to do it with out using the temporary variable, with just boolean logic, and the ever underestimated XOR (^):

  1: int a = 4;
  2: int b = 3;
  3: //Swap
  4: a = a ^ b;
  5: b = a ^ b;
  6: a = a ^ b;

Another way, with just pluses and minuses…

  1: int a = 4;
  2: int b = 3;
  3: a -= b;
  4: b += a;
  5: a = b - a;

I’ve actually seen many ways to do it, specially on this thread

2 comentarios:

  1. Its a clever idea to use XOR but I dont think it should be used in practice because it will just confuse the next developer that comes along (or you in a few months time).

    Better to use the temporary variable which as far as I know gets optimised out when you build in release mode anyway.

    ResponderEliminar
  2. That's true. You always have to keep things as simple as possible.

    ResponderEliminar

Your tips and thoughts are always welcome, and they provide good motivation: