Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

A student's question

Name: Anonymous 2011-05-30 12:20

My teacher keeps drilling into our collective heads that using the break command is harmful, and that if we wish to terminate a loop early it would be far better to create a boolean variable, set it to 0, and add a condition to the head of the loop, and set the boolean variable to 1 when a break is needed. Note that this way you actually have to check this every single loop (where it is not needed almost every time) as well as waste a command to reset the boolean in case it was set to true.

Is there a reason to this?

Name: Anonymous 2011-05-30 17:19

>>1
this:

for(int ii=0; ii<1000; ii++) {
    for(int jj=0; jj<1000; jj++) {
        for(int kk=0; kk<1000; kk++) {
            if(wantToBreak) goto loopEnd;
        }
    }
}
loopEnd:
...

is by some considered bad. However i prefer this solution over:

needToBreak = false
for(int ii=0; ii<1000 && !needToBreak; ii++) {
    for(int jj=0; jj<1000 && !needToBreak; jj++) {
        for(int kk=0; kk<1000 && !needToBreak; kk++) {
            if(wantToBreak) needToBreak = true;
        }
    }
}

and definitely instead of

needToBreak = false
for(int ii=0; ii<1000 && !needToBreak; ii++) {
    for(int jj=0; jj<1000 && !needToBreak; jj++) {
        for(int kk=0; kk<1000 && !needToBreak; kk++) {
            if(wantToBreak) {
                needToBreak = true;
                break
            }
        }
        if(needToBreak) break;
    }
    if(needToBreak) break;
}


bottom line: break is fine as long as you want to break from non-nested loop

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List