如何退出 C++ 中的 void 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/346613/
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 do you exit from a void function in C++?
提问by Jason Taylor
How can you prematurely exit from a function without returning a value if it is a void function? I have a void method that needs to not execute its code if a certain condition is true. I really don't want to have to change the method to actually return a value.
如果函数是 void 函数,如何在不返回值的情况下过早退出函数?我有一个 void 方法,如果某个条件为真,则不需要执行其代码。我真的不想改变方法来实际返回一个值。
回答by Mehrdad Afshari
Use a return statement!
使用返回语句!
return;
or
或者
if (condition) return;
You don't need to (and can't) specify any values, if your method returns void
.
如果您的方法返回void
.
回答by jwfearn
You mean like this?
你的意思是这样?
void foo ( int i ) {
if ( i < 0 ) return; // do nothing
// do something
}
回答by Stephen Caldwell
void foo() {
/* do some stuff */
if (!condition) {
return;
}
}
You can just use the return keyword just like you would in any other function.
您可以像在任何其他函数中一样使用 return 关键字。
回答by Amal K
I know the question is already answered and using a return
statement does the job.
But alternatively you can also include the rest of the function in the else
block of the if
condition.
我知道这个问题已经得到了回答,使用return
声明就可以了。但是,您也可以else
在if
条件块中包含函数的其余部分。