-
switch() inside while()
hello all,
say for example I have a switch() inside of a while(), and in one the the cases of my switch(), I use a break statement:
Code:
while(blah) {
switch(blah) {
case BLAH:
break;
}
}
that would break from the while loop, would it not? I'm in a situation here, because I don't know how I can break the case without breaking the loop. my cases are all very different, I must break from each of them somehow (execution can't "fall through"). I am using the switch() statement instead of a bunch of else ifs, which I would like to avoid using as much as possible (I have alot of conditions to test against).
I am thinking maybe I can change the loops conditional test (to something that will remain true after each case) and use a continue at the end where I would use the break in the case to jump to the loops conditional test and continue with the switch() (if of course the loop's test is still TRUE). but I am wondering if the continue will work on the loop if I place it inside a switch case like that?
if anyone could please help me here, it would be appreciated. thankyou in advance!
-
> that would break from the while loop, would it not?
No it wouldn't.
-
run this code to understand better
Code:
#include<stdio.h>
int main()
{
int ch;
printf("Enter 4 to exit\n");
while((ch=getchar())!=4)
{
switch(ch)
{
case 1:
printf("Inside the case 1\n");
break;
case 2:
printf("Inside the case 2\n");
break;
case 3:
printf("Inside the case 3\n");
break;
default:
printf("You entered %d but still inside the switch\n",ch);
}
printf("Enter 4 to exit\n");
}
printf("Out of While loop\n");
return 0;
}
ssharish2005
-
Code:
while(blah) {
switch(blah) {
case BLAH:
break;
}
}
The break and continue statements will work only for their directly related process. You can also break out of nested functions too.
Code:
while( 1 ) {
for ( i = 0; i < 10; i++ )
{
switch(blah) {
case 1:
break; //break out of the switch
case 2:
break;
break; //break from the switch and the for
case 3:
break;
break:
break; //break from the switch, for and while
}
}
}
-
really? dunno why I thought it would break the while(), I remember reading somewhere that a break inside any loop nesting will break out of the closest loop's block.
anyways, good to know that that will not break my loop, and here I was doing it the hard way (I got it to work with continue, but just using break would be a better idea IMO). :rolleyes:
thanks guys!
-
>I remember reading somewhere that a break inside any loop nesting will break out of the closest loop's block.
Make that "closest loop or switch" and it would be correct.
-
Code:
case 2:
break;
break; //break from the switch and the for
Incorrect. The second break statement will never be reached since the first break statement transfers execution to the end of the switch block.
-
Thanks bithub. For some reason I really thought I read that somewhere. If I did, it was obviously wrong.