Valid, but worthless syntax in switch-case?

后端 未结 8 1437
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-30 03:38

Through a little typo, I accidentally found this construct:

int main(void) {
    char foo = \'c\';

    switch(foo)
    {
        printf(\"Cant Touch This\\n\");         


        
8条回答
  •  北荒
    北荒 (楼主)
    2021-01-30 04:02

    You got your answer related to the required gcc option -Wswitch-unreachable to generate the warning, this answer is to elaborate on the usability / worthyness part.

    Quoting straight out of C11, chapter §6.8.4.2, (emphasis mine)

    switch (expr)
    {
    int i = 4;
    f(i);
    case 0:
    i = 17;
    /* falls through into default code */
    default:
    printf("%d\n", i);
    }
    

    the object whose identifier is i exists with automatic storage duration (within the block) but is never initialized, and thus if the controlling expression has a nonzero value, the call to the printf function will access an indeterminate value. Similarly, the call to the function f cannot be reached.

    Which is very self-explanatory. You can use this to define a locally scoped variable which is available only within the switch statement scope.

提交回复
热议问题