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.,上面的代码中这样写,在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;

}










本文转自 jiu~ 博客园博客,原文链接:http://www.cnblogs.com/jiu0821/p/6845283.html,如需转载请自行联系原作者
目录
相关文章
|
6月前
|
网络协议 网络安全 数据库
|
8月前
|
机器学习/深度学习 Java Android开发
记录一个Flutter运行的异常FAILURE: Build failed with an exception. What went wrong: A problem occurred config
记录一个Flutter运行的异常FAILURE: Build failed with an exception. What went wrong: A problem occurred config
243 0
|
Java Android开发 Windows
成功解决eclipse启动报错 Error:Could not create the Java Virtual Machine Error:A fatal exception has occurred
成功解决eclipse启动报错 Error:Could not create the Java Virtual Machine Error:A fatal exception has occurred
解决:Oops internal error 40343 occured.Further work is not possible and IDA will close (打开文件出现40343错误)
解决:Oops internal error 40343 occured.Further work is not possible and IDA will close (打开文件出现40343错误)
404 0
|
Java
Error: A JNI error has occurred, please check your installation and try again
Error: A JNI error has occurred, please check your installation and try again
213 0
解决办法:configure: error: You requested SRTP (requires libsrtp) but not found...die
解决办法:configure: error: You requested SRTP (requires libsrtp) but not found...die
150 0
warning: C4819的解决办法
warning: C4819的解决办法
135 0
svn报错:“Previous operation has not finished; run ‘cleanup‘ if it was interrupted“ 的解决办法
svn报错:“Previous operation has not finished; run ‘cleanup‘ if it was interrupted“ 的解决办法
262 0
svn报错:“Previous operation has not finished; run ‘cleanup‘ if it was interrupted“ 的解决办法
解决:Oops! internal error 40343 occured.Further work is not possible and IDA will close(打开文件出现40343错误)
解决:Oops! internal error 40343 occured.Further work is not possible and IDA will close(打开文件出现40343错误)
684 0
解决:Oops! internal error 40343 occured.Further work is not possible and IDA will close(打开文件出现40343错误)