25

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?

Ates Goral
  • 137,716
  • 26
  • 137
  • 190
Shadi
  • 441
  • 3
  • 8
  • 13

8 Answers8

37

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

Headshota
  • 21,021
  • 11
  • 61
  • 82
  • 24
    Note that `return` works even if the function has a `void` return type. You just write `return;` in that case. – In silico Jun 10 '11 at 05:14
10

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

Eskey Eski
  • 97
  • 6
Stuti
  • 1,620
  • 1
  • 16
  • 33
5

use return;:

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

AC2MO
  • 1,627
  • 13
  • 15
4

Just use return.

More info can be found here.

MD Sayem Ahmed
  • 28,628
  • 27
  • 111
  • 178
2

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

Ates Goral
  • 137,716
  • 26
  • 137
  • 190
1

Simply use return statement that return nothing. Like:

if(predicate)
return;
Fiju
  • 416
  • 1
  • 5
  • 11
1

break is to exit a loop or a switch construct.

Instead, use return with an optional value.

alex
  • 479,566
  • 201
  • 878
  • 984
0

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; 
    } 
}
K.C.
  • 2,084
  • 2
  • 25
  • 38
Sachin
  • 1