Is there an easy way to break out on an if statement, like for or while loop?

Viewed 63

I want to be able to break out of an if statement (A) if c() is true.

I sketched some code here, which would do what I want, however with a very ugly loop. Is there any way I can do the equivalant, as fast as possible without a loop? Requirements:

  1. c() should only be called if a() and b() are true. They should all be called once.
  2. Without writing or reading an external variable.
    //statement A
    if (a()) {
            //always repeats once, dirty solution.
            for (int i = 0; i < 1; i++) {
                if (b()) {
                    if (c()) {
                        break;
                    } else {
                        //code
                    }
                }
                //code (if b() and c() are true, then this should be unreachable.)
            }
        }

I am going to repeat this code about 1000 times a second, for hours. So it that is the reason behind the performance.

3 Answers

An if statement can be labelled (as can all statements). You can then use a labelled break to jump to after the if:

someLabel: if (condition) {
   // ...
   break someLabel;
   // ...
}
// It will continue from here.

However, this is not a very standard thing to do: consider restructuring your code so you can avoid having to use this.

I'd extract this logic and use return which works as break for a method, depending on what you want and what the signature of the function is, you want to use return alone, or with null or Optional.empty() or even something else

public void method() {
    if (a() && b() && c()) {
        return;
    }
    // unreachable if any of a(), b() or c() are false
}

try rewriting the inner condition in the way: b and (not c)

Related