194

How can you prematurely exit from a function without returning a value 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.

6
  • 13
    Despite that this is a really simple question, I upvoted because I had the same problem when I wrote my first C program :) Commented Dec 6, 2008 at 19:55
  • 13
    @itsbunnies: As mentioned elsewhere, there are no programming questions too simple to be asked on SO. If you had trouble with it, so has someone else in the past and so will someone else in the future. Commented Dec 6, 2008 at 21:24
  • @BilltheLizard: What about the first program who ever had that problem? Who had that problem in his past? ;-) Commented Jun 1, 2013 at 0:01
  • 1
    just had this question myself :) Commented May 16, 2015 at 10:03
  • 1
    Note you can always rewrite a function to always return at the bottom, which is a structured programming principle (one point of entry, one point of exit), Commented Jan 29, 2017 at 8:09

3 Answers 3

237

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Even more to the point: you must NOT specify any return value if your method returns void.
Aha, so when we write return; not returning anything means returning void itself eh? void means nothing anyway!! Hmm I get it now.
@quantum321 I think the return value is technically undefined, not void but thinking of it as "void" is useful.
@Dr.PersonPersonII by 'if your method returns "void"', I meant the purely syntactical view of the method's return type declared as void. Technically, the method does not return anything. which is different from returning undefined.
Actually you can write return void() too :)
15

You mean like this?

void foo ( int i ) {
    if ( i < 0 ) return; // do nothing
    // do something
}

Comments

14
void foo() {
  /* do some stuff */
  if (!condition) {
    return;
  }
}

You can just use the return keyword just like you would in any other function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.