C++ 如何跳出函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6302227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to break out of a function
提问by Shadi
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?
当我使用 break 时,它给了我一个错误。是否有另一种方法可以使用 if 条件退出函数并正常完成代码编译?
回答by Headshota
break is used in loops and switch statement. use return
instead.
break 用于循环和 switch 语句。使用return
来代替。
回答by Stuti
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
在 switch 或 for 循环的情况下使用'break'正常执行
Use 'exit'for force stop in execution
使用'exit'强制停止执行
回答by AC2MO
use return;
:
使用return;
:
if(/*condition*/) { return; }
if(/*condition*/) { return; }
回答by Ates Goral
In C++, you can return
from a function any time you want.
在 C++ 中,您可以随时return
从函数中获取。
回答by Fiju
Simply use return
statement that return nothing.
Like:
只需使用return
不返回任何内容的语句。喜欢:
if(predicate)
return;
回答by Sachin
Simply set the increment variable to a number that causes the loop to break. For example-
只需将 increment 变量设置为导致循环中断的数字。例如-
void calculate() {
for(i=0;i<10;i++) {
i=11;
}
}
回答by alex
break
is to exit a loop or a switch
construct.
break
是退出循环或switch
构造。
Instead, use return
with an optional value.
相反,使用return
可选值。