如果函数是void函数,如何在不返回值的情况下过早退出函数?我有一个void方法,如果某个条件为真,它不需要执行它的代码。我真的不想更改方法来实际返回一个值。
发布于 2008-12-06 19:10:12
使用return语句!
return;
或
if (condition) return;
如果你的方法返回void
,你不需要(也不能)指定任何值。
发布于 2008-12-06 19:10:45
你是说像这样吗?
void foo ( int i ) {
if ( i < 0 ) return; // do nothing
// do something
}
发布于 2008-12-06 19:11:52
void foo() {
/* do some stuff */
if (!condition) {
return;
}
}
您可以像在任何其他函数中一样使用return关键字。
https://stackoverflow.com/questions/346613
复制相似问题