How to break out of a function

2020-05-26 04:44发布

问题:

If I have a function as follows:

void func () {
    //...

    if (condition) {
        break;
    }
}

When I use break it gives me an error. Is there another way to exit a function using an if condition and to complete compiling the code normally?

回答1:

break is used in loops and switch statement. use return instead.



回答2:

Try to use 'return' in place of break when you want to run rest of code normally.

Use 'break' in case of switch or for loop for normal execution

Use 'exit' for force stop in execution



回答3:

use return;:

if(/*condition*/) { return; }



回答4:

Just use return.

More info can be found here.



回答5:

In C++, you can return from a function any time you want.



回答6:

Simply use return statement that return nothing. Like:

if(predicate)
return;


回答7:

break is to exit a loop or a switch construct.

Instead, use return with an optional value.



回答8:

Simply set the increment variable to a number that causes the loop to break. For example-

void calculate() { 
    for(i=0;i<10;i++) { 
       i=11; 
    } 
}