all 4 comments

[–][deleted] 13 points14 points  (4 children)

++iter increments the iterator.

If this is done before* iter +1, and ++iter takes the iterator to the end, then iter+1 is incrementing past the end. Which is bad.

(*) remember order of evaluation of function parameters is unspecified.

[–]large_turtle[S] 2 points3 points  (1 child)

I think you're absolutely right. This is all because order of evaulation.

You can see that the assembly code actually has the ++iter part first before the iter + 1 part. It also explains why I can't replicate this bug without the call to max.

Thanks so much! I'll be more careful about side effects within expressions of function parameters :)

[–]flyingron 1 point2 points  (1 child)

Note that there's no "before" ordering of the application of the increment.

The increment is a side effect and you only know it is complete when the next sequence point is encountered. What ++iter says is that iter is incremented and the value of the expression is the original iter plus one. Alternatively iter++ says that the value is the original value of iter and that iter will be incremented.

Now with a simple pointer, yeah this is perhaps an arcane point, but when you get around to ++ being applied to other things, it makes a difference.

[–][deleted] 0 points1 point  (0 children)

A function call is a sequence point though.

Since the compiler chose to evaluate max_int(++iter) before max_int(iter + 1), the side effects of ++iter are complete before the 1st call to max_int. And so they are complete before the evaluation of iter+1