error C2630: initialization of 'k' is skipped by 'case' label 错误的原因及解决方法

在 VC中遇到“error C2630: initialization of 'k' is skipped by 'case' label”的编译错误。

MSDN说明如下:
compiler error c2360 : initialization of identifier is skipped by case label
the specified identifier initialization can be skipped in a switch statement.
it is illegal to jump past a declaration with an initializer unless the declaration is enclosed in a block.
the scope of the initialized variable lasts until the end of the switch statement unless it is declared in an enclosed block within the switch statement.

the following is an example of this error:

void func( void ) 
{ 
    int x; 
    switch ( x ) 
    { 
    case 0 : 
      int i = 1;     // error, skipped by case 1   
      { int j = 1; }   // ok, initialized in enclosing block 
    case 1 : 
      int k = 1;     // ok, initialization not skipped 
    } 
}

在switch语句内定义一个变量的时候,如果不在一个语句块内,它是直到遇到switch的"}"才结束的。
int i = 1;错误,错就错在它是以switch的"}"结束的,此时被case 1:语句跳过,int i = 1不会被初始化。
int j = 1;它是遇到下面的"}"就结束了,因此正确。
int k = 1;它虽然没有在一个语句块中,但它的下一个结束"}"正好就是switch的"}",不会被跳过,因此也正确。

解决方案:1.如果有在case内定义新变量,最好将该条case内的语句加上{}构成语句块,避免出错!

     2.在case外部定义变量。

转载于:https://www.cnblogs.com/CoolSummer/archive/2012/11/22/2782864.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值