Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit from while loop without break in C

Tags:

c

while-loop

I have the following code:

void takeOrder(void)
{
int stop = 0;
while(stop != 1)
{
    printf("What is your order?\n");
    printf("%c - fruitShake\n%c - milkShake\n", FRUIT_SHAKE_CHOICE, MILK_SHAKE_CHOICE); 
    scanf("%c", &typeChoice); 
    if(typeChoice != FRUIT_SHAKE_CHOICE || typeChoice != MILK_SHAKE_CHOICE)
    {
        printf("***Error! Wrong type***");
        stop = 1;
    }
    //more code below
}

}

I'm trying to exit the while-loop with the flag "stop", but it doesn't work and it simply continues with the rest of the code below. Is there any way to exit this while-loop with a flag and without using break?

like image 325
Haim Lvov Avatar asked Dec 01 '17 15:12

Haim Lvov


2 Answers

You can do it in several ways, all of which are grossly inferior to using break:

  • You could add else and increase code nesting of the // more code part, or
  • You could set the variable and use continue instead of break to confuse your readers, or
  • You could add a label and use goto to infuriate your co-workers

The best approach is to use break, and drop the stop variable altogether, replacing it with a "forever" loop:

for (;;) {
    ...
    if (condition) {
        break;
    }
    ...
}

This construct is idiomatic in situations when none of the three built-in loop give you a particularly good fit, i.e. when the decision to break or continue is made in the middle of the loop, as opposed to the top of the loop (as in for and while loops) or the bottom of the loop (as in do/while loop).

Note: The reason why your code does not end the loop when you set the variable is that loop condition is not checked continuously. Rather, it is checked once before each iteration begins. After that the condition may become invalid at any point inside the body of the loop.

like image 91
Sergey Kalinichenko Avatar answered Oct 25 '22 14:10

Sergey Kalinichenko


The only way I see is to put in conditional the more code below part

 int stop = 0;

 while (stop != 1) {
   if (typeChoice == FRUIT_SHAKE_CHOICE || typeChoice == MILK_SHAKE_CHOICE) {
     stop = 1;
   } else {
     // more code below
   }
 }

The second only way using a function :

while (doStuff() == 0);

int doStuff(void) {
   if (typeChoice == FRUIT_SHAKE_CHOICE || typeChoice == MILK_SHAKE_CHOICE) {
     return 1;
   } 

   // more code below

   return 0;
}

PS: Maybe I'm a nazi but this should definitely be a do ... while

 int stop = 0;

 do {
   if (typeChoice == FRUIT_SHAKE_CHOICE || typeChoice == MILK_SHAKE_CHOICE) {
     stop = 1;
   } else {
     // more code below
   }
 } while (stop != 1);
like image 32
Orelsanpls Avatar answered Oct 25 '22 12:10

Orelsanpls