When using inside a for-loop, is there any exception or even extreme corner case that postincrement is actually better than preincrement?

StackOverflow https://stackoverflow.com/questions/17333153

Question

Consider the following statements:

for (Container<Object>::Iterator it = container.begin(); it != container.end(); it++) {
    *loop_content*
}

vs.

for (Container<Object>::Iterator it = container.begin(); it != container.end(); ++it) {
    *loop_content*
}

From my understanding, regardless what *loop_content* is, when used inside a for-loop like the example above, the preincrement version is guaranteed to be not worse than the postincrement version. Is there any exception or even extreme corner case that make this statement no longer true and make postincrement is actually better than preincrement?

If not so, here is my slightly off-topic second question which I have been wondering for years: Why a lot text books are teaching people to use for-loop with example like:

for (int i = 0; i < 42; i++)

not

for (int i = 0; i < 42; ++i)

My guess is that there are some medieval languages only have i++ but not ++i implemented so that people who used to these languages stay with the way they increment iterators, but I really want to know where this convention come from.

Was it helpful?

Solution 2

Usually post-increment and pre-increment differ in only two respects: they return a different value, and post-increment is slightly more expensive because it requires making a copy of the variable. The return value is not used in a for loop, so if we want post- to be better than pre-, we must invent a new Container class whose Iterator has a weird and costly pre-increment operator. Something like

operator++()
{
  ptr = ptr->next;
  // perform some undefined behavior, or just hash the Beijing telephone book
  return *this;
}

This can be done as a result of simple incompetence. As for a real reason to put something bad in operator++(), I'm stumped.

P.S. I had a subordinate once who insisted that post-increment was correct, and that using pre-increment in the for loop would give different (wrong) results. Repeatedly correcting him didn't help; the fact that he could have tested this hypothesis very easily made no difference. He had somehow worked as a software engineer for over ten years without getting good at it.

OTHER TIPS

To elaborate on my comment, a for loop like

for (pre; cond; post) body

is equivalent to the following while loop

{
    pre

    while (cond)
    {
        body
        post
    }
}

As you can see, the post part, while inside the while loop body, is separate from the for loop body.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top