-3

Let's say I have variable holding 3 and another holding 5. I need to switch their values without another variable. How can I do it?

Kevin
  • 53,822
  • 15
  • 101
  • 132
Nir Levi
  • 13
  • 1

1 Answers1

1

It can be done using bitwise XOR:

x ^= y;
y ^= x;
x ^= y;

This is known as the XOR swap algorithm (that Wikipedia article goes into detail about how this works, so I suggest you read it).

However, this isn't particularly understandable (not to mention it only works on integral types), so in nearly all contexts using a temporary variable would be preferred:

int tmp = x;
x = y;
y = tmp;
arshajii
  • 127,459
  • 24
  • 238
  • 287