Search code examples
javagoto

Avoid `goto` in a loop with "break and not execute code after loop"


Goto must be avoided. But there are cases where you cannot avoid it, without ugly code.

Consider this case:

When an expression inside a loop, is true, loop must break.

If expression inside loop is always false, after loop end, a code must be run.

Is there a nice way to do this without goto?

for (int x = 0; x < input.length; ++x)
    if (input[x] == 0) goto go_here;  // this is pseudocode. goto is not allowed in java
// execute code
go_here:

My solution is this:

both:
do {
    for (int x = 0; x < input.length; ++x)
        if (input[x] == 0) break both;
    // execute code
} while(false);

Another solution is this:

boolean a = true;
for (int x = 0; x < input.length; ++x)
    if (input[x] == 0) { a = false; break; }
if (a) {
    // execute code
}

Another inefficient solution (similar to goto) is this:

try {
    for (int x = 0; x < input.length; ++x)
        if (input[x] == 0) throw new Exception();
    // execute code
} catch(Exception e) {}

Solution

  • Here is another solution:

    both: {
        for (int x = 0; x < input.length; ++x)
            if (input[x] == 0) break both;
        // execute code
    }
    

    A block statement is a statement, so you can give it a label.