Coding Style – Does This Justify Goto Statements?

coding-stylegoto

I came across this question a second ago, and I'm pulling some of the material off of there: Is there a name for the 'break n' construct?

This appears to be a needlessly complex way for people to have to instruct the program to break out of a double-nested for loop:

for (i = 0; i < 10; i++) {
    bool broken = false;
    for (j = 10; j > 0; j--) {
        if (j == i) {
            broken = true;
            break;
        }
    }
    if (broken)
        break;
}

I know textbooks like to say goto statements are the devil, and I'm not fond of them at all myself, but does this justify an exception to the rule?

I'm looking for answers that deal with n-nested for loops.

NOTE: Whether you answer yes, no, or somewhere in between, completely close-minded answers are not welcome. Especially if the answer is no, then provide a good, legitimate reason why (which is not too far from Stack Exchange regulations anyway).

Best Answer

The apparent need for a go-to statement arises from you choosing poor conditional expressions for the loops.

You state that you wanted the outer loop to continue as long i < 10 and the innermost one to continue as long as j > 0.

But in reality that's not what you wanted, you simply didn't tell the loops the real condition you wanted them to evaluate, then you want to solve it by using break or goto.

If you tell the loops your true intentions to begin with, then no need for breaks or goto.

bool alsoThis = true;
for (i = 0; i < 10 && alsoThis; i++)
{    
    for (j = 10; j > 0 && alsoThis; j--)
    {
        if (j == i)
        {
            alsoThis = false;
        }
    }
}
Related Topic