I have a range of memory to parse. If I find a certain sequence of bytes before the end, I interrupt the iteration. I wonder which loop I should prefer here:
while(i < end && !sequenceFound ) {
// parse
i++;
}
Or
for( i; i < end && !sequenceFound; i++ ) {
// parse
}
This is used in a method of a class that derives from a class that implements a ring buffer. The superclass provides i and end. My question is, which one do you think is easier to understand (expresses the intend better) for someone unfamiliar with the code?
Edit The fact that I found the sequence is needed for the further parsing of the stream. I could use break and set sequenceFound = true, but that would be redundant, or am I being to strict here?
Why not just use
break;at the point that the need to “interrupt” the loop is encountered. This seems like the language feature that most idiomatically expresses your intent. It usually means that you can do without the extra boolean state tracking variable.If you need to know whether the iteration terminated early you can use the condidition
i != end.Either way, using the control method that is clearest would seem best andbreak;at the point at which you want to break seems clearest to me, whether or not you maintain an “early exit” variable. It seems redundant to carry on round the loop and test a condition that you’ve only just guaranteed will fail.