C with an expression using a non-compound statement?

You can write a C-switch statement with a non-compound subtitle:

int x = 2; int y = 3; int main() { switch (x) y++; // ok switch (x) case 2: y++; // ok } 

Is there any precedent for this? That is, is there ever a reason to use a non-compound subrecord of a switch statement?

+6
source share
2 answers

The first switch block in the code does nothing.

When the switch statement expression is evaluated, the source code that is present before the matching case label or default label appears will be ignored. Therefore, the β€œBefore case” statement is not printed in the program below.

 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 
+1
source

"The control passes to the operator, the case expression constant-expression corresponds to the value of the switch (expression). [...] The execution of the body of the statement begins with the selected statement and continues to the end of the body or until the break statement transfers control from the body." ( http://msdn.microsoft.com/ )

I don't think the first switch does something ... When I compiled it, y was 4, which means that it only incremented it once.

+1
source

Source: https://habr.com/ru/post/958207/


All Articles