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.
-
13Despite that this is a really simple question, I upvoted because I had the same problem when I wrote my first C program :)rmeador– rmeador2008-12-06 19:55:50 +00:00Commented 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.Bill the Lizard– Bill the Lizard2008-12-06 21:24:50 +00:00Commented Dec 6, 2008 at 21:24
-
@BilltheLizard: What about the first program who ever had that problem? Who had that problem in his past? ;-)Sparkette– Sparkette2013-06-01 00:01:04 +00:00Commented Jun 1, 2013 at 0:01
-
1just had this question myself :)moldovean– moldovean2015-05-16 10:03:56 +00:00Commented May 16, 2015 at 10:03
-
1Note 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),Malcolm McLean– Malcolm McLean2017-01-29 08:09:49 +00:00Commented Jan 29, 2017 at 8:09
|
Show 1 more comment
3 Answers
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.
5 Comments
Jonathan Leffler
Even more to the point: you must NOT specify any return value if your method returns void.
quantum231
Aha, so when we write return; not returning anything means returning void itself eh? void means nothing anyway!! Hmm I get it now.
SO Stinks
@quantum321 I think the return value is technically undefined, not void but thinking of it as "void" is useful.
Mehrdad Afshari
@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.Lightness Races in Orbit
Actually you can write
return void() too :)