1

I have a similar while loop to the one below I have looked all over does anyone know? A break statement has to be used within the loop itself that I have figured but what possible ways are there to exit a while loop from a function call as I can't seem to find any, is it possible or do I just go for a do while loop instead.

#include <iostream>
using namespace std;
int someinput=1;
int state=2;

void ifcondtionismetbreak(int x){
    if (x == 1)
    {
        // EXIT WHILE LOOP SOLUTION
    }
    else 
    {
       cout <<"Continue";
    }
}

int main() {

   while (state==2){
      cout << "This was Printed\n";
      ifcondtionismetbreak(someinput);
      cout << "Don't Print This When Condition Wants to Exit Loop\n";
   }

   return 0;
}
Shrikanth N
  • 652
  • 3
  • 17
TrevorLee
  • 231
  • 2
  • 13
  • 1
    you could throw an exception and catch it outside the loop. – Olivier Sohn Jul 20 '18 at 08:41
  • `bool ifcondtionismetbreak(int x){...` and `if (ifcondtionismetbreak(someinput)) break;` – Daniel Langr Jul 20 '18 at 08:43
  • 1
    Don't (try to) write code that way. Breaking out of a loop by an exit (or whatever) inside a function called inside the loop is spaghettification of the first order. And whatever will you do when you want to call the function not inside that loop ? Far better would be an equivalent to `if (loop_exit_condition_is_met()) break`, i.e. make it explicit in the code of the loop what is going on. – High Performance Mark Jul 20 '18 at 08:44
  • If you do not change `state` you will not be able to do that because breaking a loop cannot be done outside that loop. You could do something like `int ifcondtionismetbreak(int x) { if (x==1) return 0` and catch that value in your while loop or use a boolean – Hearner Jul 20 '18 at 08:44
  • Yeah the "state" variable will change, I just need a solution to stop the code below the function call from being executed when "input = 1;" – TrevorLee Jul 20 '18 at 08:54

2 Answers2

3

It is impossible to directly break out of a loop from within a function using a break statement. You can return a bool from your function

bool ifcondtionismetbreak(int x) {
    if (x == 1)
        return true;

    return false;
 }

and query this return value in the loop:

while (state == 2) {
    if (ifcondtionismetbreak(someinput))
        break;
    cout << "Don't Print This When Condition Wants to Exit Loop\n";
}
lubgr
  • 37,368
  • 3
  • 66
  • 117
3

You can make the function bool and if it returns true break the loop.

 #include <iostream>
 using namespace std;
 int someinput=1;
 int state=2;

 bool ifcondtionismetbreak(int x){
 if (x == 1)
 {
      return true;
 }
 else 
 {
  cout <<"Continue";
  return false;
 }
 }

 int main() {

 while (state==2){
 cout << "This was Printed\n";

 if ( ifcondtionismetbreak(someinput) )
     break;

 cout << "Don't Print This When Condition Wants to Exit Loop\n";
 }

 return 0;
 }
dimo raichev
  • 570
  • 5
  • 15