It is possible to write a C switch statement with a non-compound sub-statement:
int x = 2;
int y = 3;
int main()
{
switch (x)
y++; // ok
switch (x)
case 2: y++; // ok
}
Is there any use case for this? That is, is there ever a reason to use a non-compound sub-statement of a switch statement?
You can use have both CASE statements as follows. FALLTHROUGH: Another point of interest is the break statement. Each break statement terminates the enclosing switch statement.
The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc. Float and double are not allowed. The case statements and the default statement can occur in any order in the switch statement.
If the switch condition doesn't match any condition of the case and a default is not present, the program execution goes ahead, exiting from the switch without doing anything. Show activity on this post.
Microsoft C doesn't limit the number of case values in a switch statement. The number is limited only by the available memory. ANSI C requires at least 257 case labels be allowed in a switch statement.
The first switch block in the code doesn't do anything.
When switch statement expression is evaluated, the source code present until the occurrence of matching case label or default label, will be ignored. Hence it doesn't print statement "Before case" in the below program.
int x = 2;
int y = 3;
int main()
{
switch (x)
{
y++;
printf("Before case");
case 2:
printf("In case 2");
break;
}
return 0;
}
Output:
In case 2
"Control passes to the statement whose case
constant-expression matches the value of switch
( expression ). [...] Execution of the statement body begins at the selected statement and proceeds until the end of the body or until a break
statement transfers control out of the body." (http://msdn.microsoft.com/)
I don't think the first switch
does anything... When I compiled it, y
was 4, which means it only incremented it once.
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