2

Possible Duplicate:
What is the fastest way to swap values in C?

I need to exchange values of two integers (for example x and y) This is the simplest way:

int temp = x;
x = y;
y = temp;

and I also found a better way:

x = x + y;
y = x - y;
x = x - y;

Is there a better way to increase performance?

Community
  • 1
  • 1
shift66
  • 11,760
  • 13
  • 50
  • 83
  • 4
    There is **no possible way** that *either* of these pieces of code is a bottleneck in your application. – Cody Gray - on strike Dec 20 '11 at 05:57
  • 2
    Unless you're asking this out of curiosity, you're wasting effort. Trust your compiler to produce efficient code for such a trivial operation. – Michael Petrotta Dec 20 '11 at 05:58
  • possible duplicate of [What is the fastest way to swap values in C?](http://stackoverflow.com/questions/36906/what-is-the-fastest-way-to-swap-values-in-c), [Swap the values of two variables without using third variable](http://stackoverflow.com/questions/756750/swap-the-values-of-two-variables-without-using-third-variable), [Swap two variables without using a temp variable](http://stackoverflow.com/questions/804706/swap-two-variables-without-using-a-temp-variable), *etc. etc. etc.* – Cody Gray - on strike Dec 20 '11 at 06:02

2 Answers2

4

it is posible with XOR "^" operator:

  a = a^b;
  b = a^b;
  a = a^b;
Artur Keyan
  • 7,643
  • 12
  • 52
  • 65
2

Well in the second option you use 2 variables instead of 3 in the 1st option, this means you allocate less memory.

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130