Rectangle 27 83

One option is to use a condition flag. You could then either break in the outer loop as well, or just use it as an extra condition within the for loops:

bool keepGoing = true;

for (int col = 0; col < 8 && keepGoing; col++)
{
    for (int row = 0; row < 8 && keepGoing; row++)
    {
        if (something)
        {
             // Do whatever
             keepGoing = false;
        }
    }
}

In Java you can specify a label to break to though. (I didn't see that this question was tagged Java as well as C#.)

outerLoop:
for (...)
{
    for (...)
    {
        if (...)
        {
            break outerLoop;
        }
    }
}

EDIT: As noted in comments, in C# you could use a label and goto:

for (...)
{
    for (...)
    {
        if (...)
        {
            goto endOfLoop;
        }
    }
}
endOfLoop:
// Other code

I'd really recommend that you don't take either of these approaches though.

In both languages it would usually be best to simply turn both loops into a single method - then you can just return from the method:

public void doSomethingToFirstOccurrence()
{
    for (...)
    {
        for (...)
        {
            if (...)
            {
                return;
            }
        }
    }
}

@3D-kreativ: Yes, but I'd still recommend using the "extract to method" approach.

@3D-kreativ Yes, return exits the current method instantly. Except if you have a finally block, in which case the content of the finally block will be executed before exiting the current method, which is meant for closing open connections or disposing of objects or the likes.

@Gusdor: Readability is about much more than just line count. Often you can find a relatively long method can be broken into several short methods each of which tackles a single aspect, and one "coordinator" method which just calls each method in turn. While the code ends up being longer, it can be much quicker to read that way.

c# - Possible to use break for outer loop? - Stack Overflow

c# java
Rectangle 27 44

You can find all sorts of professional code with 'break' statements in them. It perfectly make sense to use this whenever necessary. In your case this option is better than creating a separate variable just for the purpose of coming out of the loop.

Is it a bad practice to use break in a for loop? - Stack Overflow

for-loop break
Rectangle 27 7

I agree with others who recommend using break. The obvious consequential question is why would anyone recommend otherwise? Well... when you use break, you skip the rest of the code in the block, and the remaining iterations. Sometimes this causes bugs, for example:

Every now and then people observing such bugs realise they can be prevented/mitigated by this "no breaks" rule... indeed, there's a whole related strategy for "safer" programming called "structured programming", where each function is supposed to have a single entry and exit point too (i.e. no goto, no early return). It may eliminate some bugs, but it doubtless introduces others. Why do they do it?

  • they have a development framework that encourages a particular style of programming / code, and they've statistical evidence that this produces a net benefit in that limited framework, or
  • they've been influenced by programming guidelines or experience within such a framework, or
  • any of the above + historical inertia (relevant in that the justifications are more applicable to C than modern C++).

Well, yeah, but then again I've seen bugs in code by people who religiously tried to avoid break. The did avoid it but failed to think through the conditions that replaced the use of break.

Is it a bad practice to use break in a for loop? - Stack Overflow

for-loop break
Rectangle 27 7

In your example you do not know the number of iterations for the for loop. Why not use while loop instead, which allows the number of iterations to be indeterminate at the beginning?

It is hence not necessary to use break statemement in general, as the loop can be better stated as a while loop.

A "for" loop is often good if there's a known maximum number of iterations. That having been said, a while(1) loop is sometimes better in a scenario where one is searching for an item and plans to create it if it doesn't exist. In that case, if the code finds the item it does a direct break, and if it hits the end of the array it creates a new item and then does a break.

In the example given -- searching through an array for a key, the for loop is the proper idiomatic construct. You don't use a while loop to walk through an array. You use a for loop. (or a for-each loop if available). You do this as a courtesy to other programmers, as they recognize the "for (int i=0; i < ra.length; i++){}" construct immediately as "Walk through the array" Adding a break, to this construct is simply a "Quit early if you can" statement.

Is it a bad practice to use break in a for loop? - Stack Overflow

for-loop break
Rectangle 27 10

break is a completely acceptable statement to use (so is continue, btw). It's all about code readability -- as long as you don't have overcomplicated loops and such, it's fine.

It's not like they were the same league as goto. :)

I have seen it argued that a break statement is effectively a goto.

The problem with goto is that you can point it anywhere. Both break and continue preserve the modularity of the code. That argument is on the same level as having a single exit point for each function.

I've heard it argued that having multiple exit points for a function is effectively a goto. ;D

@glenatron The problem with goto isn't the goto statement, it is the introduction of the label that the goto jumps to that is the problem. Whem you read a goto statement, there is no uncertainty about control flow. When you read a label, there is lots of uncertainty about control flow (where are all the gotos that transfer control to this label?). A break statement doesn't introduce a label, so it doesn't introduce any new complications.

The "break" is a specialzied goto that can only leave blocks. The historical problems with "goto" were (1) it could be, and often was, used to construct overlapping loop blocks in a way that isn't possible with proper control structures; (2) a common way to do an "if-then" construct which was usually "false" was to have the true case branch off to an unrelated place in the code, and then branch back. This would cost two branches in the rare case, and zero in the common case, but it made the code look hideous.

Is it a bad practice to use break in a for loop? - Stack Overflow

for-loop break
Rectangle 27 11

There is nothing inherently wrong with using a break statement but nested loops can get confusing. To improve readability many languages (at least Java does) support breaking to labels which will greatly improve readability.

int[] iArray = new int[]{0,1,2,3,4,5,6,7,8,9};
int[] jArray = new int[]{0,1,2,3,4,5,6,7,8,9};

// label for i loop
iLoop: for (int i = 0; i < iArray.length; i++) {

    // label for j loop
    jLoop: for (int j = 0; j < jArray.length; j++) {

        if(iArray[i] < jArray[j]){
            // break i and j loops
            break iLoop;
        } else if (iArray[i] > jArray[j]){  
            // breaks only j loop
            break jLoop;
        } else {
            // unclear which loop is ending
            // (breaks only the j loop)
            break;
        }
    }
}

I will say that break (and return) statements often increase cyclomatic complexity which makes it harder to prove code is doing the correct thing in all cases.

If you're considering using a break while iterating over a sequence for some particular item, you might want to reconsider the data structure used to hold your data. Using something like a Set or Map may provide better results.

.NET programmers might want to explore the use of LINQ as a potential alternative to complex for loops.

Is it a bad practice to use break in a for loop? - Stack Overflow

for-loop break
Rectangle 27 41

You cannot use break; this way, it must appear inside the body of the for loop.

There are several ways to do this, but neither is recommended:

An acceptable alternative is to pass the address of a status variable as an extra argument: the function can set it to indicate the need to break from the loop.

But by far the best approach in C is returning a value to test for continuation

From your explanations, you don't have the source code for foo() but can detect some conditions in a function that you can modify called directly or indirectly by foo(): longjmp() will jump from its location, deep inside the internals of foo(), possibly many levels down the call stack, to the setjmp() location, bypassing regular function exit code for all intermediary calls. If that's precisely what you need to do to avoid a crash, setjmp() / longjmp() is a solution, but it may cause other problems such as resource leakage, missing initialization, inconsistent state and other sources of undefined behavior.

Note that your for loop will iterate 101 times because you use the <= operator. The idiomatic for loop uses for (int i = 0; i < 100; i++) to iterate exactly the number of times that appears as the upper (excluded) bound.

It should be emphasized that evaluating a return value is absolutely the way to go, as it yields best readability.

c - Breaking out of a loop from within a function called in that loop ...

c for-loop break
Rectangle 27 4

In the embedded world, there is a lot of code out there that uses the following construct:

while(1)
    { 
         if (RCIF)
           gx();
         if (command_received == command_we_are_waiting_on)
           break;
         else if ((num_attempts > MAX_ATTEMPTS) || (TickGet() - BaseTick > MAX_TIMEOUT))
           return ERROR;
         num_attempts++;
    }
    if (call_some_bool_returning_function())
      return TRUE;
    else
      return FALSE;

This is a very generic example, lots of things are happening behind the curtain, interrupts in particular. Don't use this as boilerplate code, I'm just trying to illustrate an example.

My personal opinion is that there is nothing wrong with writing a loop in this manner as long as appropriate care is taken to prevent remaining in the loop indefinitely.

Could you elaborate on that? It looks to me as if the loop does absolutely nothing... unless there are continue statements inside the application logic. Are there?

continue statements are unnecessary as you are already bound by an infinite loop. You basically perform the necessary logic required to achieve a goal and if that goal is not met in n number of attempts or a timeout condition expires, you exit the loop via a break construct and take corrective action or inform the calling code of an error. I see this type of code often in uCs that communicate via a common bus (RS-485, etc.) You basically attempt to seize the line and communicate without collisions, if collisions happen, you wait a duration determined by a random number and try again.

Conversely, if things go well, you also use the break statement to exit once the condition has been met. Given this case, the code following the loop is executed and everyone is happy.

Is it a bad practice to use break in a for loop? - Stack Overflow

for-loop break
Rectangle 27 205

No, don't spoil it with a break. This is the last remaining stronghold for the use of goto.

The MISRA C++ coding standard allows the use of goto to cover this exact kind of situation.

Real programmers are not afraid to use goto. Done it for 25 years -- no regrets -- saved a ton of development time.

I agree. gotos are a must if you do not have 8K pixels across, and need to call a sequence of 30 Windows OS calls.

c++ - Can I use break to exit multiple nested for loops? - Stack Overf...

c++ for-loop break nested-loops
Rectangle 27 3

Depends on your use case. There are applications where the runtime of a for loop needs to be constant (e.g. to satisfy some timing constraints, or to hide your data internals from timing based attacks).

In those cases it will even make sense to set a flag and only check the flag value AFTER all the for loop iterations have actually run. Of course, all the for loop iterations need to run code that still takes about the same time.

If you do not care about the run time... use break; and continue; to make the code easier to read.

If timing is important you may be better off doing some sleeps and save system resources than let the program do known-to-be-useless operations.

Is it a bad practice to use break in a for loop? - Stack Overflow

for-loop break
Rectangle 27 105

Good lord no. Sometimes there is a possibility that something can occur in the loop that satisfies the overall requirement, without satisfying the logical loop condition. In that case, break is used, to stop you cycling around a loop pointlessly.

String item;

for(int x = 0; x < 10; x++)
{
    // Linear search.
    if(array[x].equals("Item I am looking for"))
    {
       //you've found the item. Let's stop.
       item = array[x];
       break; 
    }
}

What makes more sense in this example. Continue looping to 10 every time, even after you've found it, or loop until you find the item and stop? Or to put it into real world terms; when you find your keys, do you keep looking?

Edit in response to comment

Why not set x to 11 to break the loop? It's pointless. We've got break! Unless your code is making the assumption that x is definitely larger than 10 later on (and it probably shouldn't be) then you're fine just using break.

Edit for the sake of completeness

There are definitely other ways to simulate break. For example, adding extra logic to your termination condition in your loop. Saying that it is either loop pointlessly or use break isn't fair. As pointed out, a while loop can often achieve similar functionality. For example, following the above example..

while(x < 10 && item == null)
{
    if(array[x].equals("Item I am looking for"))
    {
        item = array[x];
    }

    x++;
}

Using break simply means you can achieve this functionality with a for loop. It also means you don't have to keep adding in conditions into your termination logic, whenever you want the loop to behave differently. For example.

for(int x = 0; x < 10; x++)
{
   if(array[x].equals("Something that will make me want to cancel"))
   {
       break;
   }
   else if(array[x].equals("Something else that will make me want to cancel"))
   {
       break;
   }
   else if(array[x].equals("This is what I want"))
   {
       item = array[x];
   }
}

Rather than a while loop with a termination condition that looks like this:

while(x < 10 && !array[x].equals("Something that will make me want to cancel") && 
                !array[x].equals("Something else that will make me want to cancel"))

The OP also asked about something akin to setting x to 1000 to break the loop/

What about a while loop instead of a break? Then all loop completion conditions are right at the start of the loop. while(x < 10 && item == null) of if you're feeling fancy, use an iterator.

@Freiheit : you can use it or even you may improve it. But I think example given by Chris is for OP's understanding.

@hexafraction : what if I want to use x index in code below the loop? e.g. found string at index x

@NandkumarTekale Then you'll need to declare it outside and break out of the loop with it intact.

Is it bad practice to use break to exit a loop in Java? - Stack Overfl...

java loops jvm break
Rectangle 27 4

It's perfectly valid to use break - as others have pointed out, it's nowhere in the same league as goto.

Although you might want to use the vFound variable when you want to check outside the loop whether the value was found in the array. Also from a maintainability point of view, having a common flag signalling the exit criteria might be useful.

Is it a bad practice to use break in a for loop? - Stack Overflow

for-loop break
Rectangle 27 4

In my opinion a For loop should be used when a fixed amount of iterations will be done and they won't be stopped before every iteration has been completed. In the other case where you want to quit earlier I prefer to use a While loop. Even if you read those two little words it seems more logical. Some examples:

for (int i=0;i<10;i++) {
    System.out.println(i);
}
for (int i=0;i<10;i++) {
    if (someCondition) break;
    System.out.println(i);
}

This one is already less clear to me. Why would you first state you will take 10 iterations, but then inside the loop add some extra conditions to stop sooner?

I prefer the previous example written in this way (even when it's a little more verbose, but that's only with 1 line more):

int i=0;
while (i<10 && !someCondition) {
    System.out.println(i);
    i++;
}

Everyone who will read this code will see immediatly that there is an extra condition that might terminate the loop earlier.

Ofcourse in very small loops you can always discuss that every programmer will notice the break statement. But I can tell from my own experience that in larger loops those breaks can be overseen. (And that brings us to another topic to start splitting up code in smaller chunks)

This doesn't take into account the situation where a condition is reached DURING the for or while loop. If the for/while loop triggers a condition (or perhaps something being executed on another thread) then you may have to break early. The while loop you wrote assumes that you only have to check the condition at the beginning of an iteration.

I totally agree with this. If you have a for loop, the intention is that the logic for the initialisation, condition and increment are together in one place. This saves having to look here there and everywhere to find exactly what may be going on. If you do not know how many times you are wanting to loop, then you are looping "while" something, therefore it should be a while loop. If you are looping until something, it should be a do while. I am not suggesting at all that breaks are bad practise, but there is a time and a place for them.

Is it bad practice to use break to exit a loop in Java? - Stack Overfl...

java loops jvm break
Rectangle 27 166

AFAIK, C++ doesn't support naming loops, like Java and other languages do. You can use a goto, or create a flag value that you use. At the end of each loop check the flag value. If it is set to true, then you can break out of that iteration.

Don't be afraid to use a goto if that is the best option.

I'm a new C++ programmer (and one without any formal programming training) thus after reading about people's rants on goto. I'm hesitant on using it in fear my program might just suddenly explode and kill me. Other than that, when i used to write programs on my ti-83 (in boring math class of course), the functions the basic editor provided required the use of goto's.

@Faken: Two types of programmers use goto: Bad programmers, and pragmatic programmers. The former are self explanatory. The latter, which you would fit into if you choose to use them well, use a so called "evil" concept when it is the lesser of (two) evils. Read this for a better understanding of some C++ concepts that you might need to use from time to time (macros, goto's, preprocessor, arrays): parashift.com/c++-faq-lite/big-picture.html#faq-6.15

@Faken: There's nothing wrong with using goto. It's misusing a goto that is troublesome.

@Hooked: That's right, except that using goto rarely ever is the best option. Why not put the loops into their own function (inline, if you're concerned about speed) and return from this?

c++ - Can I use break to exit multiple nested for loops? - Stack Overf...

c++ for-loop break nested-loops
Rectangle 27 27

You can add labels to your loop, and use that labelled break to break out of appropriate loop: -

outer: for (...) {
    inner: for(...) {
        if (someCondition) {
            break outer;
        }
    }
}

java - How to Break from main/outer loop in a double/nested loop? - St...

java loops syntax for-loop break
Rectangle 27 27

You can add labels to your loop, and use that labelled break to break out of appropriate loop: -

outer: for (...) {
    inner: for(...) {
        if (someCondition) {
            break outer;
        }
    }
}

java - How to Break from main/outer loop in a double/nested loop? - St...

java loops syntax for-loop break
Rectangle 27 110

agreed. Especially if you are looking to exit the loop under more than a single condition. The boolean to leave a loop can get really confusing then.

That is why I use goto to break out of Level 2+ nested loops - because there is not break(level)

I'd rather put the loop code in a function, and just return. This avoids the goto, and breaks your code into smaller chunks.

Is it a bad practice to use break in a for loop? - Stack Overflow

for-loop break
Rectangle 27 41

Using break as well as continue in a for loop is perfectly fine.

It simplifies the code and improves its readability.

Yes.. For a time I didn't like the idea and coded around it, but it didn't take long before I realized the... "workaround" was often a maintenance nightmare. Well, not a nightmare, but more error-prone.

Is it a bad practice to use break in a for loop? - Stack Overflow

for-loop break
Rectangle 27 78

Lots of answers here, but I haven't seen this mentioned yet:

Most of the "dangers" associated with using break or continue in a for loop are negated if you write tidy, easily-readable loops. If the body of your loop spans several screen lengths and has multiple nested sub-blocks, yes, you could easily forget that some code won't be executed after the break. If, however, the loop is short and to the point, the purpose of the break statement should be obvious.

If a loop is getting too big, use one or more well-named function calls within the loop instead. The only real reason to avoid doing so is for processing bottlenecks.

Quite true. Of course if the loop is so big and complex that it's difficult to see what's happening inside it, that's a problem whether you have a break or not.

Another issue is that break and continue cause problems with refactoring. This might be a sign that this is a bad practice. The intent of the code is also clearer when using if statements.

Those "well-named function call(s)" can be locally-defined lambda functions instead of externally-defined private functions that won't be used elsewhere.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Is it a bad practice to use break in a for loop? - Stack Overflow

for-loop break
Rectangle 27 6

A simple example would be where you are looping through objects in an array, looking for one that satisfies a certain condition. When you've found that object, you don't need to check the rest so use break.

Why do we use breaks in JavaScript loops? - Stack Overflow

javascript loops for-loop break