How do you exit from a void function in C++?

c++

Question

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.

1
147
4/15/2018 10:44:43 AM

Accepted Answer

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.

181
11/4/2009 1:09:44 PM

You mean like this?

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon