How to break out of a function

2020-05-26 05:15发布

If I have a function as follows:

void func () {
    //...

    if (condition) {
        break;
    }
}

When I use break it gives me an error. Is there another way to exit a function using an if condition and to complete compiling the code normally?

8条回答
一纸荒年 Trace。
2楼-- · 2020-05-26 05:22

Try to use 'return' in place of break when you want to run rest of code normally.

Use 'break' in case of switch or for loop for normal execution

Use 'exit' for force stop in execution

查看更多
孤傲高冷的网名
3楼-- · 2020-05-26 05:25

break is to exit a loop or a switch construct.

Instead, use return with an optional value.

查看更多
Melony?
4楼-- · 2020-05-26 05:36

break is used in loops and switch statement. use return instead.

查看更多
劳资没心,怎么记你
5楼-- · 2020-05-26 05:38

In C++, you can return from a function any time you want.

查看更多
祖国的老花朵
6楼-- · 2020-05-26 05:39

Simply set the increment variable to a number that causes the loop to break. For example-

void calculate() { 
    for(i=0;i<10;i++) { 
       i=11; 
    } 
}
查看更多
做个烂人
7楼-- · 2020-05-26 05:40

Simply use return statement that return nothing. Like:

if(predicate)
return;
查看更多
登录 后发表回答