Whenever I need to break out from a for(unsigned int i=0;i<bound;++i)
expression in C++, I simply set the index variable i=bound
, the same way as described in this answer. I tend to avoid the break
statement because, honestly, I have no good understanding of what it actually does.
Compare the two instructions:
for(unsigned int i=0;i<bound;++i) {
if (I need a break) {
break;
}
}
and
for(unsigned int i=0;i<bound;++i) {
if (I need a break) {
i=bound;
}
}
I speculate that the second method does one extra variable set and then one extra comparison between i
and bound
, so it looks more expensive, from performance point of view. The question is then is it cheaper to call break
, then doing these two tests? Are the compiled binaries any different? Is there any instance, where the second method breaks, or can I safely choose either of these two alternatives?
Related: Does `break` work only for `for`, `while`, `do-while`, `switch' and for `if` statements?