switch (i){case 0:int j; // 'j' has indeterminate valuej = 0; // 'j' set (not initialized) to 0, but this statement// is jumped when 'i == 1'break;case 1:++j; // 'j' is in scope here - but it has an indeterminate valuebreak;}
如果对象是非POD或聚合,编译器会隐式添加一个初始化器,因此不可能跳过这样的声明:
class A {public:A ();};
switch (i) // Error - jumping over initialization of 'A'{case 0:A j; // Compiler implicitly calls default constructorbreak;case 1:break;}
此限制不仅限于Switch语句。使用'goto'跳过初始化也是错误的:
goto LABEL; // Error jumping over initializationint j = 0;LABEL:;
#include <iostream>
using namespace std;
int test1(){int i = 0;// There jumps fo "case 1" and "case 2"switch(i) {case 1:// Compile error because of the initializerint r = 1;break;case 2:break;};}
void test2(){int i = 2;switch(i) {case 1:int r;r= 1;break;case 2:cout << "r: " << r << endl;break;};}
int main(int argc, const char *argv[]){test1();test2();return 0;}
switch (value) {case 1:int a = 10;break;case 2:int a = 20;break;}
这可能令人惊讶,但编译器不会将其视为简单的if/else if。它将生成以下代码:
if (value == 1)goto label_1;else if (value == 2)goto label_2;elsegoto label_end;
{label_1:int a = 10;goto label_end;label_2:int a = 20; // Already declared !goto label_end;}
label_end:// The code after the switch block