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?
You can do it in several ways, all of which are grossly inferior to using break
:
else
and increase code nesting of the // more code
part, orcontinue
instead of break
to confuse your readers, orgoto
to infuriate your co-workersThe 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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With