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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:53:21  来源:igfitidea点击:

How to break out of a function

c++functionreturnbreak

提问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 returninstead.

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 MD Sayem Ahmed

Just use return.

只需使用return.

More info can be found here.

更多信息可以在这里找到。

回答by Ates Goral

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

在 C++ 中,您可以随时return从函数中获取。

回答by Fiju

Simply use returnstatement 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

breakis to exit a loop or a switchconstruct.

break是退出循环或switch构造。

Instead, use returnwith an optional value.

相反,使用return可选值。