Coding Tricks and Interviewing

My post on stupid coding tricks elicited some interesting responses, both in the comments to the post and in a discussion held in the forums over in Joel’s web site. Some of the responses, like Eric Albert’s, focused on the interview question. Others, like this one from Dennis Atkins, took issue with my assessment of the validity of the xor trick as C/C++ code.

As I’d said, I’m no compiler writer, so I’m not necessarily qualified to discuss which clauses in the official C and C++ language definitions apply. However, here’s my take. The expression is:

a ^= b ^= a ^= b;

Within that expression, there are two assignments to a. The question is, which value of b is used in the evaluation of the second assignment to a? The answer to that question, to my thinking anyway, involves deciding which of the xor subexpressions gets evaluated first before the second assignment to a takes place. Since the order of evaluation of these subexpressions is undefined, the result of the second assignment to a is undefined.

As for whether or not this was a stupid interview question, I’ll stand by my initial assessment. For this particular line of code, the question can only have two reasonable purposes: 1) the apparent purpose, to test the candidate’s ability to figure out what xor does in this context, or 2) to test the candidate’s understanding of the formal definitions of the C and C++ languages. If the interviewer’s purpose was 1, then there are other, less ambiguous, ways to achieve the same result. If the purpose was 2, then this particular question is too esoteric to be of legitimate value to anyone but compiler writers, and I would contend that there are more important issues of interest, even to people writing compilers, than this particular issue.

That said, while I’m on the subject of technical interviews, an experience I had as an interviewer may well be helpful to people seeking employment. I gave a particular programming problem to an interview candidate who then went straight to the white-board and wrote a solution to the problem. While the solution was correct, it wasn’t the optimal solution.

I asked the candidate why he wrote that solution, and he said that he didn’t know, but at his former employer they’d decided that this was the way it had to be done. That left me with the unpleasant task of trying to find a way to consume the remaining 30 minutes of time we’d allocated for the interview.

If your approach to problem solving is the bang-on-the-toaster variety, then don’t bother trying to interview for a programming position. You’d probably be far happier as a tester. For programmers, we want people whose approach is to take the toaster apart and figure out how it works.

Rick