Valid, but worthless syntax in switch-case?

后端 未结 8 1425
爱一瞬间的悲伤
爱一瞬间的悲伤 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:09

    Not only for variable declaration but advanced jumping as well. You can utilize it well if and only if you're not prone to spaghetti code.

    int main()
    {
        int i = 1;
        switch(i)
        {
            nocase:
            printf("no case\n");
    
            case 0: printf("0\n"); break;
            case 1: printf("1\n"); goto nocase;
        }
        return 0;
    }
    

    Prints

    1
    no case
    0 /* Notice how "0" prints even though i = 1 */
    

    It should be noted that switch-case is one of the fastest control flow clauses. So it must be very flexible to the programmer, which sometimes involves cases like this.

提交回复
热议问题