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

后端 未结 3 1028
醉话见心
醉话见心 2021-01-29 22:26

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 i

相关标签:
3条回答
  • 2021-01-29 23:03

    You mean like this?

    void foo ( int i ) {
        if ( i < 0 ) return; // do nothing
        // do something
    }
    
    0 讨论(0)
  • 2021-01-29 23:08
    void foo() {
      /* do some stuff */
      if (!condition) {
        return;
      }
    }
    

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

    0 讨论(0)
  • 2021-01-29 23:13

    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.

    0 讨论(0)
提交回复
热议问题