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

C++

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

You mean like this?

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

Solution 3 - C++

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJason TaylorView Question on Stackoverflow
Solution 1 - C++mmxView Answer on Stackoverflow
Solution 2 - C++jwfearnView Answer on Stackoverflow
Solution 3 - C++Stephen CaldwellView Answer on Stackoverflow