Why can't variables be declared in a switch statement?

后端 未结 23 2968
一生所求
一生所求 2020-11-21 05:15

I\'ve always wondered this - why can\'t you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring

23条回答
  •  你的背包
    2020-11-21 06:12

    You can't do this, because case labels are actually just entry points into the containing block.

    This is most clearly illustrated by Duff's device. Here's some code from Wikipedia:

    strcpy(char *to, char *from, size_t count) {
        int n = (count + 7) / 8;
        switch (count % 8) {
        case 0: do { *to = *from++;
        case 7:      *to = *from++;
        case 6:      *to = *from++;
        case 5:      *to = *from++;
        case 4:      *to = *from++;
        case 3:      *to = *from++;
        case 2:      *to = *from++;
        case 1:      *to = *from++;
                   } while (--n > 0);
        }
    }
    

    Notice how the case labels totally ignore the block boundaries. Yes, this is evil. But this is why your code example doesn't work. Jumping to a case label is the same as using goto, so you aren't allowed to jump over a local variable with a constructor.

    As several other posters have indicated, you need to put in a block of your own:

    switch (...) {
        case FOO: {
            MyObject x(...);
            ...
            break; 
        }
        ...
     }
    

提交回复
热议问题