error:crosses initialization of ...

switch(c)

{

      case 0x01:

      int temp = a + b;

      ....

      break;

      case 0x02:

      break;

      default:break;

}

此时会报如题所示错误

原因是因为C和C++中,一个变量的生命期(作用域)是这么规定的,中文还不好解释,英文原文是这样的:The scope of a variable extends from the point where it is defined to the first closing brace that matches the closest opening brace before before the variable was defined.,原文http://zhubangbing.blog.163.com/blog/static/5260927020109821055992/,上面的代码中这样写,在case 0x02中temp仍然有效,看看编译器提示的信息 cross initialization of int temp, 什么意思呢, 就是说跳过了变量的初始化,仔细想想,确实是这样,我们在case 1中定义了变量temp,在这个程序中,直到遇到switch的“}”右花括号,temp的作用域才终结,也就是说 在case 2 和 default 分支中 变量temp依然是可以访问的。考虑这样一种情况,如果switch匹配了case 2,这样case 1的代码被跳过了,那么temp就没有定义,如果此时在case 2的代码中访问了temp,程序会崩溃的。所以上面的程序应写成如下方式

switch(c)

{

      case 0x01:

     {

      int temp = a + b;

      ....

     }//这样的话temp的生命期到这里就结束了,在后面的case中temp就是未定义的,如果用到,编译阶段就会有提示

      break;

      case 0x02:

      break;

      default:break;

}

 

http://zhubangbing.blog.163.com/blog/static/526092702011931821900/

https://blog.csdn.net/zzwdkxx/article/details/27561393

少壮不识cpp,老大方知cpp可怕
原文地址:https://www.cnblogs.com/Jacket-K/p/9149987.html