c++loopsoff-by-one

Are these two loops equivalent: off-by-one


Are these two loops the same? For some reason the second loop is off-by-one and I cannot figure out why.

while ( !b && ++n < WORD_COUNT ) b = mWords[n];
n++;
while ( !b && n < WORD_COUNT ) {
    b = mWords[n];
    n++;
}

Solution

  • When the predicate b was not successful, then a logic short-circuit may apply in the first form and the final increment of n may be skipped.

    In the second form, the increment happens before predicate b is evaluated, so n is off-by-one when the loop exits.