re: Terrible interview question: Swap variables without a temporary VIEW POST


In C, that invokes undefined behaviour by modifying a more than once between sequence points, and is - unfortunately - an incorrect answer.


"It works as I'd expect it to, having not read The Specification, but having been told it's UB, on my compiler" is but one possible outcome of Undefined Behaviour, yes.

But you cannot rely on it

tbh I hate interview questions like these. I explicitly deny to solve them and explain interviewers that language quirks have nothing to do with product making (I don't usually work for outsourcers, I'd rather create something from scratch).

I think that program code is intended for humans, not computers. So I write it myself accordingly.

Even if it worked and was reliable, I can't even imagine the real world product-making, non-scientific and non-algorithmic task that requires swapping variables. I'd rather stick to mapping and filtering. And even if I needed swapping, I'd rather make it as obvious as possible.

So yes, it's unreliable. Just as unreliable as virtually any code that is not straightforward.

code of conduct - report abuse