如果函数是void函数,如何在不返回值的情况下提前退出函数?我有一个void方法,如果某个条件为真,则不需要执行其代码.我真的不想更改实际返回值的方法.
Meh*_*ari 184
使用return语句!
return;
Run Code Online (Sandbox Code Playgroud)
要么
if (condition) return;
Run Code Online (Sandbox Code Playgroud)
如果方法返回,则不需要(也不能)指定任何值void.
jwf*_*arn 12
你的意思是这样的?
void foo ( int i ) {
if ( i < 0 ) return; // do nothing
// do something
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*ell 10
void foo() {
/* do some stuff */
if (!condition) {
return;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以像使用任何其他函数一样使用return关键字.