One of the very tricky questions asked in an interview.
Swap the values of two variables like a=10
and b=15
.
Generally to swap two variables values, we need 3rd variable like:
temp=a;
a=b;
b=temp;
Now the requirement is, swap values of two variables without using 3rd variable.
No-one has suggested using
std::swap
, yet.I don't use any temporary variables and depending on the type of
a
andb
the implementation may have a specalization that doesn't either. The implementation should be written knowing whether a 'trick' is appropriate or not. There's no point in trying to second guess.More generally, I'd probably want to do something like this, as it would work for class types enabling ADL to find a better overload if possible.
Of course, the interviewer's reaction to this answer might say a lot about the vacancy.