Here's the code:
#include <stdio.h>
int main ()
{
int menu=0;
while (menu!=3)
{
scanf ("%d", &menu);
switch (menu)
{
case 1:
{
printf ("Case 1\n");
continue;
}
case 2:
{
printf ("Case 2\n");
break;
}
}
printf ("This doesn't get printed by case 1\n");
}
return 0;
}
Every time I put it 1, that printf won't show up, but other than that, it works well. So how continue
and break
works for switch
inside a loop
? Why break
doesn't break the loop? Instead, it prevents the next cases to be done right? But what about continue
? To be clear, I'm actually asking how is it different and how those actually work. Note: I've done this too in java (with eclipse).
B (and thereafter its descendants including C++, Java or JavaScript) overloads the break
keyword to jump out of switch
es.
So when you're in a nested loop/switch
situation, the break
keyword will apply to the innermost switch
or loop, whichever is closer.
This overload is an accident of history. B started by copying BCPL and while BCPL later gained an endcase
keyword design specifically for breaking switch
es, Thompson and Ritchie were not aware of the change and so B and C remained with their home-made readaptation of break
for this purpose.
( http://port70.net/~nsz/c/c89/dmr_the_development_of_the_c_language.pdf
Not every difference between the BCPL language documented in Richards’s book [Richards79] and B was deliberate; we started from an earlier version of BCPL [Richards 67]. For example, the endcase that escapes from a BCPL switchon statement was not present in the language when we learned it in the 1960s, and so the overloading of the break keyword to escape from the B and C switch statement owes to divergent evolution rather than conscious change.
)
In any case, in B/C/C++, break
/continue
is nothing but syntactic sugar for a goto
and if you want to break
/continue
something other than the innermost loop/switch
, you can always achieve it by using an explicit goto
:
#include <stdio.h>
int main ()
{
int menu=0;
while (menu!=3)
{
scanf ("%d", &menu);
switch (menu)
{
case 1:
{
printf ("Case 1\n");
continue;
}
case 2:
{
printf ("Case 2\n");
goto break_loop;
//`return 0;` would work too in this case
break; //would break out of the switch
}
}
printf ("This doesn't get printed by case 1\n");
}
break_loop:
return 0;
}