Hi all,
I've been following the discussions concerning loops and
whether to break or terminate mimicking the condition etc.
I've had this recent case (which caused a bug) where I
had to do something on checking the condition, whereafter
exiting (the loop).
It went something like this:
for( Sequence::iterator i = mySeq.begin(); i != mySeq.end(); ++i )
{
i->doSomething();
if( *i->hasCertainCondition() )
{
i->doSomethingElse();
//essentially break out.
i = mySeq.end(); //Force terminate :-)
}
}
All in all the loop was more complicated, but this suffices the
example.
This caused a crash (as I recall). <iincremented after the loop was
completed whereafter the condition were checked. The increment of <i>
caused incrementing past the end (causing assertion).
I suppose there are other ways in which this could be done, but
<break>
statement would have solved the problem and would not have caused the
bug. Just merely (or naively perhaps) trying to be conventional caused
the
bug.
Of course one could have used (i = mySeq().end - 1), but <break>
seems less error prone to me.
It could also be noted that the loop is quite a rare case, where you
want to do something for each item, and if this causes the item
to change state, you want to do something else and then not
continue. Other possibilities that sprung to mind were:
Sequence::iterator i = mySeq.begin();
for( i; (i != mySeq.end()) && (not i->hasCertainCondition()); ++i )
{
i->doSomething();
}
//if loop terminated early, doSomethingElse
if( i != mySeq.end() )
{
i->doSomethingElse();
}
Using the original loop with a break seemed the cleanest to me. I've
noticed some "perhaps respected" posters shuns this approach.
What would you in general consider "the cleaner" solution?
One that I certainly don't consider cleaner is forcing the
termination
condition (as this is more error prone than break).
Regards,
Werner