There are several postings concerning switch statements within while loops, except for the fact that none of them are done in C, at least from what I've seen. C++ can create boolean expressions, which I'm aware of, but not in C. I have a while loop that contains a switch control. However, when I write break statements within my switch, it goes back to the beginning of the loop and makes my program run forever. Ignore the functions I use, for they work for sure. I just need some clarification on my handling of the nesting. Thanks!
Here is my main.c:
while(1)
{
printf("0) Exit\n1) List Tasks\n2) Add Task\n");
printf("3)Delete Task\n4) Add Task From File\n");
printf("What would you like to do?\n");
fgets(buf1, 50, stdin);
p = atoi(buf1);
switch(p)
{
case 0:
break;
case 1:
printTaskList(pTaskList);
break;
case 2:
printf("Enter task name: ");
fgets(buf2,100,stdin);
printf("Enter task priority: ");
fgets(buf3,100,stdin);
printf("Enter task start date: ");
fgets(buf4,50,stdin);
pTask = makeTask(buf2,buf4,buf3);
addTaskToEnd(pTaskList,pTask);
break;
case 3:
printTaskList(pTaskList);
printf("What task would you like to delete? ");
fgets(buf6,50,stdin);
taskNum = atoi(buf6);
removeTask(pTaskList,taskNum);
break;
case 4:
printf("Enter the filename ");
fgets(buf7,50,stdin);
break;
default:
printf("ERROR: %d: Incorrect menu option\n", p);
}
}
Yes a switch statement can be used inside a loop.
The break statement is usually used with the switch statement, and it can also use it within the while loop, do-while loop, or the for-loop. The continue statement is not used with the switch statement, but it can be used within the while loop, do-while loop, or for-loop.
We can also use nested switch i.e. switch inside a switch. If the case constants of both inner and outer switch have same value, no problem will arise.
break;
will exit out of the nearest enclosing switch
or loop. To jump two levels, you'll have to use the dreaded goto
, or reorganize so a return
will accomplish the desired semantics.
while(1) {
switch(x) {
case 0: goto EndWhile;
}
}
EndWhile: ;
Or
void loop() {
while(1) {
switch(x) {
case 0: return;
}
}
}
//...
loop();
//...
You can totally use a Boolean expression in C. Just use an int
.
int quit = 0;
while(!quit) {
switch(x) {
case 0: quit = 1; break;
}
}
C also has a boolean data type, if you really want it.
#include <stdbool.h>
bool quit = false;
while(!quit) {
switch(x) {
case 0: quit = true; break;
}
}
And one more option, for the totally insane.
#include <setjmp.h>
jmp_buf jbuf;
if (!setjmp(jbuf))
while(1) {
switch(x) {
case 0: longjmp(jbuf, 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