How to break out of a function

旧街凉风 提交于 2019-12-03 11:15:02

问题


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?


回答1:


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




回答2:


use return;:

if(/*condition*/) { return; }




回答3:


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




回答4:


Just use return.

More info can be found here.




回答5:


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




回答6:


break is to exit a loop or a switch construct.

Instead, use return with an optional value.




回答7:


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; 
    } 
}



回答8:


Simply use return statement that return nothing. Like:

if(predicate)
return;


来源:https://stackoverflow.com/questions/6302227/how-to-break-out-of-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!