首页
社区
课程
招聘
[旧帖] [求助]switch-case 中变量声命问题,求深入讲解下。 0.00雪花
发表于: 2012-5-3 18:48 1354

[旧帖] [求助]switch-case 中变量声命问题,求深入讲解下。 0.00雪花

2012-5-3 18:48
1354
大家看下面的代码,红色部分在VC6中会报错:error C2360: initialization of 'hwnd' is skipped by 'case' label
  switch(uMsg) {
  case WM_INITDIALOG:
    [COLOR="Red"]HWND hwnd = GetDlgItem(hwndDlg,IDC_NAME);  [/COLOR]  
    // TODO: Place code here.
    break;
  case WM_CLOSE:
    EndDialog(hwndDlg,0);
    break;
  }

改成下面这种就没问题:
  switch(uMsg) {
  case WM_INITDIALOG:
    [COLOR="Red"]HWND hwnd;
    hwnd = GetDlgItem(hwndDlg,IDC_NAME);[/COLOR]    
    // TODO: Place code here.
    break;
  case WM_CLOSE:
    EndDialog(hwndDlg,0);
    break;
  }

这两种声名的方式,到底差别在那,编译器实现switch-case语句为什么第一种就会报错,感觉没什么不同呀。不知道怎么问好,能从变量的内存分布分配方面讲解下最好,或者说这只是编译器的一个小BUG。碰到这种错误好几次了,一直纠结啊

[结贴啦,自己找到了点资料,有兴趣的可以去看下]http://blog.csdn.net/tonywearme/article/details/7075809

[培训]《安卓高级研修班(网课)》月薪三万计划,掌握调试、分析还原ollvm、vmp的方法,定制art虚拟机自动化脱壳的方法

收藏
免费 0
支持
分享
最新回复 (2)
雪    币: 2
活跃值: (10)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
2
你好象是说反了吧?应该是:上面的没错,下面的就有错。
因为涉及跳转,编译器在编译的时候,存在一个变量先声明和后声明的问题。为了解决这个问题,switch规定变量必须先于switch声明,否则在里边声明就会出错。
解决办法

HWND hwnd;//先于switch声明。
switch(XXX)
{
case XX:........
}

还有一种方法是:
switch(XXX)
{
case XX:
      {
       HWND hwnd;//由于声明是局部的,所以不受switch的影响,但只能在这里用。
       ........
       }
}
2012-5-4 16:32
0
雪    币: 110
活跃值: (25)
能力值: ( LV3,RANK:20 )
在线值:
发帖
回帖
粉丝
3
没有说反呀,第一种报错,第二种编译能通过。
找了点材料,好像是什么变量呀,初始化呀,跳转呀,搞的问题。谁给翻译下,看的懵懵懂懂的
It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer. (The transfer from the condition of a switch statement to a case label is considered a jump in this respect.)
2012-5-4 19:57
0
游客
登录 | 注册 方可回帖
返回
//