How can you prematurely exit from a function 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.
+26
A:
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
.
Mehrdad Afshari
2008-12-06 19:10:11
Well then, I feel like a complete idiot now. Thank you.
Jason Taylor
2008-12-06 19:13:13
StackOverflow rule: There is no stupid question.
Mehrdad Afshari
2008-12-06 19:14:25
+1 for no stupid questions!
Nils Pipenbrinck
2008-12-06 20:09:24
Even more to the point: you must NOT specify any return value if your method returns void.
Jonathan Leffler
2009-04-19 20:16:06
+2
A:
You mean like this?
void foo ( int i ) {
if ( i < 0 ) return; // do nothing
// do something
}
jwfearn
2008-12-06 19:10:44
A:
void foo() {
/* do some stuff */
if (!condition) {
return;
}
}
You can just use the return keyword just like you would in any other function.
Stephen Caldwell
2008-12-06 19:11:51
A:
I got taught that multiple exit points (return statements) inside functions are generally bad because it makes code hard to follow and debug. I guess it's probably just a styling choice / personal preference, and if you are trying to optimize code for speed it would make sense to return ASAP. But anyway, a single exit point alternative to @jwfearn's answer is
void myFunction(int i)
{
if (i > 0)
{
// do something
}
}
mrnye
2009-11-04 13:17:11