EMC Interview Question
Developer Program EngineersCountry: United States
This works perfectly fine but fails when a is equal to b.
Should use an if condition before using this logic to check for a = b.
@mail.qurram : dude this works even if a=b;
suppose a=b=4 (100) . i.e. a=a^b makes a=000 ,b=a^b makes b=100 then a=a^b i.e (000)^(100) makes a=100...
I read about this long back. Just remember very little, but found out the actual thing which I intended to focus on. Although a very very specific case, its worth knowing it.
where you have written your code like this
swap(int *a, int *b)
{
*a ^= *b ^= *a ^= *b;
}
Now, if suppose, by mistake, your code passes the two pointers to the same variable to this function. Guess what happens? Since Xor'ing an element with itself sets the variable to zero, this routine will end up setting the variable to zero (ideally it should have swapped the variable with itself). This scenario is quite possible in sorting algorithms which sometimes try to swap a variable with itself (maybe due to some small, but not so fatal coding error). One solution to this problem is to check if the numbers to be swapped are already equal to each other.
a = a^b;
- Mir February 03, 2012b = a^b;
a = a^b;