你如何退出C++中的void函数?

Jas*_*lor 150 c++

如果函数是void函数,如何在不返回值的情况下提前退出函数?我有一个void方法,如果某个条件为真,则不需要执行其代码.我真的不想更改实际返回值的方法.

Meh*_*ari 184

使用return语句!

return;
Run Code Online (Sandbox Code Playgroud)

要么

if (condition) return;
Run Code Online (Sandbox Code Playgroud)

如果方法返回,则不需要(也不能)指定任何值void.

  • 更重要的是:如果方法返回void,则不能指定任何返回值. (2认同)
  • 其实你也可以写`return void()`:) (2认同)

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关键字.