A for loop terminates when the second expression is false
or when contextually converted to a bool value produces false
. In C++, 0 is contextually converted to false; all other integers convert to true in a bool context. (Thanks to M.M.for the link.)
So at the beginning of each loop the expression i--
is evaluated. It's just an expression, so it will produce a result. If the result it produces is zero, the loop will end. If you haven't seen this expression before, here is how it works:
- It both decrements i and returns the original value of i before it was decremented. So if
i
were 5, evaluating i--
will have the "result" 5, but as a side effect, i
will be 4 after the evaluation.
The big picture: i
is decremented by 1 each time, so assuming it starts off positive, it will get down to 0, at which time evaluating i--
will produce 0.