int main()
{
int i=4;
switch(i)
{
default:printf("zero\n");
case 1: printf("one\n");
break;
case 2:printf("two\n");
break;
case 3: printf("three\n");
break;
}
return 0;
}
Again, where is the break statement for the default case? Do you know why break makes a difference?
Regards,
Paul McKenzie
I thought case statement is like if statement. So in my example, when i is 4 and it meets case 1, then case 1 is not going to be entered. Why am I wrong? Thanks.
I thought case statement is like if statement. So in my example, when i is 4 and it meets case 1, then case 1 is not going to be entered. Why am I wrong? Thanks.
That's been answered twice by Paul and once by me already. Basically a switch statement starts at the first case that meets the expression and keeps going till it hits a break.
I thought case statement is like if statement. So in my example, when i is 4 and it meets case 1, then case 1 is not going to be entered. Why am I wrong? Thanks.
Larry, don't you see your reasoning is faulty?
OK, so what does break do? What purpose does it serve if, by your reasoning, once a case condition is met, the switch is exited as soon as the next case condition is met? If that's your conclusion, then why not just remove the break statements from case 1, case 2, and case 3? It's just unnecessary typing, according to your conclusion.
The answer is as GCDEF mentioned -- break does mean something in a case statement, and that is to ensure that the condition doesn't "fall through" to the next case condition.
This "fall through" into the next case behaviour is sometimes a very handy feature of how the switch in C++ works. (as opposed to other programming languages where this isn't possible)
Bookmarks