Valid, but worthless syntax in switch-case?

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

    It should be noted, that there are virtually no structural restrictions on the code within the switch statement, or on where the case *: labels are placed within this code*. This makes programming tricks like duff's device possible, one possible implementation of which looks like this:

    int n = ...;
    int iterations = n/8;
    switch(n%8) {
        while(iterations--) {
            sum += *ptr++;
            case 7: sum += *ptr++;
            case 6: sum += *ptr++;
            case 5: sum += *ptr++;
            case 4: sum += *ptr++;
            case 3: sum += *ptr++;
            case 2: sum += *ptr++;
            case 1: sum += *ptr++;
            case 0: ;
        }
    }
    

    You see, the code between the switch(n%8) { and the case 7: label is definitely reachable...


    * As supercat thankfully pointed out in a comment: Since C99, neither a goto nor a label (be it a case *: label or not) may appear within the scope of a declaration that contains a VLA declaration. So it's not correct to say that there are no structural restrictions on the placement of the case *: labels. However, duff's device predates the C99 standard, and it does not depend on VLA's anyway. Nevertheless, I felt compelled to insert a "virtually" into my first sentence due to this.

提交回复
热议问题