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;
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;
std::tie(x,y) = std::make_pair(y,x);
But std::swap(x,y)
is much more readable and probably more efficient.
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;
}