Can I use break to exit multiple nested for loops?

2019-01-01 08:17发布

Is it possible to use the break function to exit several nested for loops? If so, how would you go about doing this? Can you also control how many loops the break exits?

17条回答
无色无味的生活
2楼-- · 2019-01-01 08:39

One nice way to break out of several nested loops is to refactor your code into a function:

void foo()
{
    for(unsigned int i=0; i < 50; i++)
    {
        for(unsigned int j=0; j < 50; j++)
        {
            for(unsigned int k=0; k < 50; k++)
            {
                // If condition is true
                return;
            }
        }
    }
}
查看更多
爱死公子算了
3楼-- · 2019-01-01 08:41

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.

查看更多
君临天下
4楼-- · 2019-01-01 08:41

A code example using goto and a label to break out of a nested loop:

for (;;)
  for (;;)
    goto theEnd;
theEnd:
查看更多
明月照影归
5楼-- · 2019-01-01 08:42

break will exit only the innermost loop containing it.

You can use goto to break out of any number of loops.

Of course goto is often Considered Harmful.

is it proper to use the break function[...]?

Using break and goto can make it more difficult to reason about the correctness of a program. See here for a discussion on this: Dijkstra was not insane.

查看更多
皆成旧梦
6楼-- · 2019-01-01 08:46

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

查看更多
永恒的永恒
7楼-- · 2019-01-01 08:46

Other languages such as PHP accept a parameter for break (i.e. break 2;) to specify the amount of nested loop levels you want to break out of, C++ however doesn't. You will have to work it out by using a boolean that you set to false prior to the loop, set to true in the loop if you want to break, plus a conditional break after the nested loop, checking if the boolean was set to true and break if yes.

查看更多
登录 后发表回答