如何跳出函数
如果我有一个如下函数:
void func () {
//...
if (condition) {
break;
}
}
当我使用break时,它会给我一个错误。是否有另一种方法可以使用 if 条件退出函数并正常完成代码编译?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
break 用于循环和 switch 语句中。使用
return
代替。break is used in loops and switch statement. use
return
instead.当您想正常运行其余代码时,请尝试使用'return'代替break。
在 switch 或 for 循环的情况下使用 'break' 来正常执行
使用 'exit' 强制停止执行
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
使用
return;
:if(/*条件*/) { return; }
use
return;
:if(/*condition*/) { return; }
只需使用
返回
即可。更多信息可以在此处找到。
Just use
return
.More info can be found here.
在 C++ 中,您可以随时从函数
返回
。In C++, you can
return
from a function any time you want.break
是退出循环或switch
结构。相反,请使用带有可选值的
return
。break
is to exit a loop or aswitch
construct.Instead, use
return
with an optional value.只需将增量变量设置为导致循环中断的数字即可。例如-
Simply set the increment variable to a number that causes the loop to break. For example-
只需使用不返回任何内容的
return
语句即可。喜欢:
Simply use
return
statement that return nothing.Like:
使用return退出函数。
使用break退出循环。
注意:“使用break将退出循环,而return实际上会完成该方法。因此,如果您的目标只是停止循环,则可以使用break。但是,如果您希望该方法结束,请使用return。”
另请参阅:关闭函数时返回与中断?
Use return to exit from a function.
Use break to quit the loop.
Note: "Using break will quit the loop, whereas return will actually complete the method. So if your goal is to simply stop the loop, you can use break. However, if you want the method to end, use return."
See also this: Return vs break when closing a function?