Is the switch with some code written before the labels all right?

I am wondering if all compilers will silently ignore the code before the shortcuts in the switch statement, as VS2005 does.

This is what I need:

#define CASE break; case 

So,

 switch (i) { CASE 0: print("0"); CASE 1: print("1"); } 

will turn into

 switch (i) { break; case 0: print("0"); break; case 1: print("1"); } 

From the standard it seems obvious that the first "break" (and any other code there, if it existed) will not be executed. The standard does not deny the existence of such code, but I cannot be sure of real compilers.

+4
source share
2 answers

Yes, this is implied in Β§6.4.2ΒΆ5 (in particular, the ignoring part):

When the switch statement is executed, its state is evaluated and compared with each case constant. If one of the case constants is equal to the condition value, control is transferred to the operator, the next associated case label. If the case constant does not meet the condition, and if there is a default label, control passes to the statement marked with the default label. If the case does not match, and if there is no default value, none of the statements in the switch are executed.

I don't think your macro is a good idea.

+4
source

Personally, I would be "incapable" of writing such code, since all warnings turn into errors, and an invalid code warning is ... and in fact, a quick test for clang ++ generates such a warning.

+1
source

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


All Articles