1

i could do with third variable

c=a|b;
a=c&a;
b=c&a;

But i need to do it without third variable. I tried using XOR it wasn't helping me either.

No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
11user2614896
  • 59
  • 1
  • 5

2 Answers2

9

it's an easy 1st year programming class question:

a = a^b;
b = a^b;
a = a^b;
No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
6

XOR has a property that XORing something twice always brings you back to where you started. You can use this fact to switch variables in three assignments without a third variable.

int a = 54;
int b = 23;

a = a XOR b; // (a XOR b)
b = a XOR b; // (a XOR b) XOR b = a
a = a XOR b; // (a XOR b) XOR a = b
Isaac
  • 310
  • 1
  • 6