Search code examples
cswitch-statementlabeldeclarationgoto

Explanation of switch statement constraints on variably modified types in C standard


I'm writing a C compiler, and when I come to the implementation of the switch statement one constraint confused me a lot. Section 6.8.4.2p2 of the standard states:

If a switch statement has an associated case or default label within the scope of an identifier with a variably modified type, the entire switch statement shall be within the scope of that identifier.

With a footnote:

That is, the declaration either precedes the switch statement, or it follows the last case or default label associated with the switch that is in the block containing the declaration.

I can't really understand what this constraint means. Can some one give me an example?


Solution

  • What this is saying is that if one case is able to see a variably modified array, then the entire switch statement MUST be able to see it as well.

    This means that the following code is legal:

    void switch_test(int size)
    {
        int array[size];
        ...
        // code to populate array
        ...
        switch (expr) {
        case 1:
            printf("%d\n", array[0]);
            break;
        case 2:
            // do something else
        }
    }
    

    But this code is not:

    void switch_test(int size)
    {
        switch (expr) {
        case 2:
            // do something else
            int array[size];   // ILLEGAL, VLA in scope of one label but not all
        case 1:
            ...
            // code to populate array
            ...
            printf("%d\n", array[0]);
        }
    }
    

    The reason the latter is illegal is because if the code were to jump to case 1 then array might not have been created properly since the size of a VLA is determined at run time. Ensuring that the VLA is visible before the switch statement avoids this issue.