6

I'm using Java but I guess this question applies to whatever language. I just want to ask whether it's better practice to exit a loop using a boolean which I toggle within the loop or to just use break;

For example, I was just writing a method to get the valid moves for a Queen in chess.

private static final int[][] DIRS = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {-1, -1}, {-1, 1}, {1, -1}};

public Vector<Move> getValidMoves() {
    Vector<Move> validMoves = new Vector<Move>();

    for (int i = 0; i < DIRS.length; i++) {
        boolean stopped = false;
        int newX = x + DIRS[i][0];
        int newY = y + DIRS[i][1];
        while (!stopped && newX >= 0 && newX < 8 && newY >= 0 && newY < 8) {
            if (board[newX][newY] == null) {
                validMoves.add(new Move(x, y, newX, newY));
                newX += DIRS[i][0];
                newY += DIRS[i][1];
            } else {
                if (board[newX][newY].getColour() == colour) {
                    stopped = true;
                } else {
                    validMoves.add(new Move(x, y, newX, newY));
                    stopped = true;
                }
            }
        }
    }

    return validMoves;
}

If I exit the while loop using break; instead of setting stopped to true like I do it's my understanding that it runs more efficiently but is not the greatest code style.

2
  • 1
    Seing your code for the Queen, I'd say you have more to worry about than just a break statement. For instance, try to avoid Vector if you don't need Thread safe data structure (use ArrayList instead), Try to encapsulate more logic into objects (such as testing if a coordinate is on the board, along with replacing magic numbers such as "8") Commented Mar 9, 2011 at 13:28
  • Ok, thanks for the tips. I'll take them into consideration. Commented Mar 9, 2011 at 13:35

10 Answers 10

13

break exists for the sole reason of exiting a loop, I can't think of any better way to do that.

Sign up to request clarification or add additional context in comments.

2 Comments

Right on! I break all the time. That is if there's no need for more complexity.
I would like to point out that break is also used with switch ^^
8

Performance-wise, it won't matter much, you are allocating 1 boolean on the stack and adding 1 comparison at each loop iteration, so nothing to worry about.

It mainly depends on whether you want to finish executing the rest of the loop code before exiting it or not. Break will exit immediatly and setting a boolean will wait for the next iteration before stopping.

If you don't need to finish the loop iteration, your code will be easier to read if you use break

3 Comments

Since it does nothing but go to the next iteration after it is set anyway I guess break it is. Thanks Johan Sjöberg and MarvinLabs for your quick responses.
In that case, yes, I'd break
I agree. I used to fear the break keyword. For some reason I associated it with bad programming style. It seems "brutal" because it just "breakes" the loop and if it "breaks" it, isn't that bad design? After all everything should "flow".. Well it turns out break is a very elegant solution. It just took me a couple of years to see that:)
2

As using boolean variable here does not affect much for performance, this is about readability. Some people believes using break statement reduces code's readability for two reasons.

One is that user sometimes cannot read the code sequentially (need to jump read) when break statement is used. This can be confusing as reader need to determine where the break statement brings next operation to.

Another thing is that using variable for stop condition helps reader understands why it is stopped if you name the variable meaningfully. e.g if you use isEmpty boolean variable for stop condition, it is very clear that the loop has stopped because whatever is empty.

I am not against using break statement but I think what you should do is to make it readable as possible.

Comments

1

I suggest you do what you believe is clearest. IMHO Using a boolean can be clearer for nested loops, but for simple loops using a flag is needlessly verbose.

while (0 <= newX && newX < 8 && 0 <= newY && newY < 8) {
    if (board[newX][newY] == null) {
        validMoves.add(new Move(x, y, newX, newY));
        newX += DIRS[i][0];
        newY += DIRS[i][1];
    } else {
        if (board[newX][newY].getColour() != colour) 
            validMoves.add(new Move(x, y, newX, newY));
        break;
    }
}

Comments

1

Definitively use break. That is what the keyword is for, it generates more concise code, does not make someone reading your code wonder where that "stopped" in the loop comes from, and is likely faster, too.

5 Comments

Why do you say it's likely faster?
@davin: Breaking after the second iteration (for example) is arguably faster than iterating the rest of the hundreds of times... not that it'll be faster by any more than 0.01 seconds, but still.
@BoltClock, obviously continuing with useless iterations is slower than exiting (save extreme cases where checking a specific condition in itself takes long). It seems to me that the claim here is that using break in general is faster than exiting with a boolean exit condition. And I question that claim.
if(condition) break; will result in a CMP-JMP sequence, whereas while(flag){if(condition) flag = true;} will necessarily have at least the additional overhead of pushing/popping an extra variable on the stack. The variable's scope goes beyond the block, so a compiler cannot trivially skip it "because it's not used anyway". On top of that, depending on the compiler's optimization abilities, the generated code will probably be much closer to CMP-STORE-JMP-FETCH-CMP-JMP than simply CMP-JMP. It will never be faster, but likely a tiny bit slower. More importantly, however, it's harder to read.
Oh my... and I've just proven my point by writing the example above wrong... of course it has to be while(!flag){if(condition) flag = true;}. See, that is why break is superior, such a stupid typo would be avoided in the first place by using the proper keyword. Complexity is not good if the language offers something clear and concise.
1

Depends on who you talk to. I have a college professor who swore he'd shoot any student who didn't exit a control structure (such as a loop) with a normal expression check.

However, I have seen that as much as that might be "disciplined", there are times where to exit a loop or other control structure early is desireable. With that in mind, I say "go for it". You can still be disciplined and have readable code that does not have unexpected behavior with an early exit (as long as that exit would be a valid reason for leaving that structure.

Comments

1

Thats exactly why there is break in the language. I would just use it.

Comments

1

Like the users above mentioned, definitely use break. Exiting loops is what it's made for.

Comments

1

A point that seems not to have been raised yet:

In Java (not exclusively though), exiting nested loops will be more elegant with break than having the same condition nested in every level. It will also make the code more maintainable.

In addition, it can make the logic of the loop much more simple, because as soon as your come to a breaking condition you can act, rather than continue executing code. This too promotoes modularity within the loop body.

Comments

1

You may want to read up on the usage of break from the oracle webpage

Branching Statements Tutorial

using a Break to exit a loop is accept as a good practice. then if you use it or not is up to you.

now if you want to improve the readability of your code and its flexibility you can consider breaking down you complex loops into functions.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.