Are these two loops equivalent: off-by-one

43 views Asked by At

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++;
}
1

There are 1 answers

0
Ext3h On BEST ANSWER

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.