How does a FOR loop work?

During a recent round of interviews we asked candidates to point out the problem with the following code snippet

for($i = 0; $i < 10; ++$i)
  if ($i = 0)
    print "yes";

This was intended as a simple, spot-the-typo, exercise. The problem is if ($i = 0), should read if ($i == 0)! As is, it's an infinite loop, and the follow up question is to ask if it's infinitely printing "yes" or not.

Relatively easy and straightforward. What happened in the actual interviews was anything but straightforward. Without fail, candidates kept pointing out the pre-increment ++$i. My first thought was to put them back on track, because "no, that has nothing to do with it." Instead I decided to explore.

"Wait, tell me why the pre-increment would be a problem?" I asked curiously.

Every candidate seemed to have a different explanation for why a pre-increment wouldn't work. I would then ask them to walk through the execution of the loop. And this was the mistake that each candidate shared, they didn't know how a standard three-expression for loop worked.

Stubbornly, many would insist that the pre-increment would be run first, before the assignment statement. I would ask, "so the execution order of the three expressions is dependent on the third expression?", hoping they would see the absurdity in such a claim. "Yes," was the confident reply. sigh

"No," I would explain (feeling a little defeated), "the first expression is always executed first and only once, the third expression is only executed after a loop iteration."

I would go on to explain that the pre-increment works perfectly fine. In fact, there is some argument that it is more efficient since it is not creating temporary variables (a post-increment will create a temporary variable to hold the original value that is returned from the statement). Either way, in the context of a three-expression for loop it makes no difference; whichever method lends itself to better readability in your code should be used.

None of the candidates who missed this question were considered for a position.

And what did I learn? That we should use foreach with Iterator objects, and I'm switching to Python!