So I need to switch between A and B without using another integer.
I was able to do this easily with a third integer (tmp). Is there any way to do this without it?
int a = 53, b = 12, tmp = 0;
tmp = a;
a = b;
b = tmp;
So I need to switch between A and B without using another integer.
I was able to do this easily with a third integer (tmp). Is there any way to do this without it?
int a = 53, b = 12, tmp = 0;
tmp = a;
a = b;
b = tmp;
The most common mentioned method is:
y ^= x;
x ^= y;
y ^= x;
An alternative is to use addition and subtraction instead of XOR; but that's messy due to the risk of overflows.
Note: To be precise; XOR causes undefined behavior for negative values (but that can be prevented with simple casts to unsigned and back to signed); and addition/subtraction can cause overflow which is also undefined behavior, but there's no easy fix for that.
Of course no sane person would ever do this in real code (it's faster and cheaper to use a temporary variable).
Yes, there is an other way to do it:
int a=53, b=12;
a = a + b; // a = 65
b = a - b; // b = 53
a = a - b; // a = 12
You can do that using arithmetic addition and subtraction between those two variables.
int a = 53, b = 12;
a = a + b;
b = a - b;
a = a - b;