cpp error_crosses initialization of errror_jump to case label -fpermissive

⌚Time: 2023-01-10 21:32:46

👨‍💻Author: Jack Ge

问题代码

int main(){
    int i=2;
    switch(i){
    case 1:
        int j = 0;
        break;
    case 2:
        j++;
        break;
    default:
        break;
    }
    return 0;
}

报错

>g++ test.cpp
test.cpp: In function 'int main()':
test.cpp:7:7: error: jump to case label [-fpermissive]
  case 2:
       ^
test.cpp:5:7: error:   crosses initialization of 'int j'
   int j = 0;
       ^
test.cpp:10:2: error: jump to case label [-fpermissive]
  default:
  ^
test.cpp:5:7: error:   crosses initialization of 'int j'
   int j = 0;
       ^

switch语句中没有单独的区域块限制变量的生命周期,因此变量生命周期是从声明到switch结束。因此在case1中声明的变量在case2中也可以使用。 如果在case1中声明并且对其进行初始化。而运行时直接跳入case2就会导致变量不能初始化,从而导致程序运行期间的问题。编译器为了防止这个问题就会出错提示 解决办法是将变量的定义放在switch语句之前

int main(){
    int i=2;
    int j=0;
    switch(i){
    case 1:
        j = 0;
        break;
    case 2:
        j++;
        break;
    default:
        break;
    }
    return 0;
}

或者使用大括号限定变量的生命周期

int main(){
    int i=2;
    switch(i){
    case 1:
    {
        int j = 0;
    }
        break;
    case 2:
        j++;
        break;
    default:
        break;
    }
    return 0;
}