tags:

views:

4565

answers:

4

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
Well then, I feel like a complete idiot now. Thank you.
Jason Taylor
StackOverflow rule: There is no stupid question.
Mehrdad Afshari
+1 for no stupid questions!
Nils Pipenbrinck
Even more to the point: you must NOT specify any return value if your method returns void.
Jonathan Leffler
+2  A: 

You mean like this?

void foo ( int i ) {
    if ( i < 0 ) return; // do nothing
    // do something
}
jwfearn
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
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