0

How can I swap the values of two variables ?

This works, but I'd would prefer a one liner :

int a = 10, b = 30;
a = a + b;
b = a - b;
a = a - b;
k1eran
  • 4,492
  • 8
  • 50
  • 73
  • 3
    Are you under the mistaken impression that using another variable costs more than not using one? – Benjamin Lindley Mar 06 '15 at 11:44
  • How about the XORSWAP macro from the [Wikipedia page](http://en.m.wikipedia.org/wiki/XOR_swap_algorithm) on XOR Swap algorithm? Make a note to read the section about why it should be avoided in practice ;) – Paul Rooney Mar 06 '15 at 12:38

3 Answers3

4

Perhaps that's cheating but there's simply :

std::swap(a, b);
tux3
  • 7,171
  • 6
  • 39
  • 51
0
std::tie(x,y) = std::make_pair(y,x);

But std::swap(x,y) is much more readable and probably more efficient.

Jens
  • 9,058
  • 2
  • 26
  • 43
0
int main()
{
int x = 10, y = 10;
y = (x + y)-y;
}

Solved a little bit but not completely but solved if you use this code

int swap(int *x, int y){
*x = (*x + *y) - *x;
return 0;
}

int main()
{
int x = 10;
int y = 5;
y = (x + y) - y + swap(&x, &y);
cout << x << endl << y << endl;
}