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?
break is used in loops and switch statement. use return
instead.
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
use return;
:
if(/*condition*/) { return; }
Just use return
.
More info can be found here.
In C++, you can return
from a function any time you want.
Simply use return
statement that return nothing.
Like:
if(predicate)
return;
break
is to exit a loop or a switch
construct.
Instead, use return
with an optional value.
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;
}
}