错误:跳转到SWITCH语句中的CASE标签 [英] Error: Jump to case label in switch statement

查看:56
本文介绍了错误:跳转到SWITCH语句中的CASE标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个涉及Switch语句使用的程序,但是编译时显示:

错误:跳至案例标签。

为什么要这样做?

#include <iostream>
int main() 
{
    int choice;
    std::cin >> choice;
    switch(choice)
    {
      case 1:
        int i=0;
        break;
      case 2: // error here 
    }
}

推荐答案

问题是,除非使用显式的{ }挡路,否则在一个case中声明的变量在后续的case中仍然可见,但它们不会被初始化,因为初始化代码属于另一个case

在下面的代码中,如果foo等于1,则一切正常,但如果等于2,我们将意外使用确实存在但可能包含垃圾的i变量。

switch(foo) {
  case 1:
    int i = 42; // i exists all the way to the end of the switch
    dostuff(i);
    break;
  case 2:
    dostuff(i*2); // i is *also* in scope here, but is not initialized!
}

用明确的挡路包装案例解决了问题:

switch(foo) {
  case 1:
    {
        int i = 42; // i only exists within the { }
        dostuff(i);
        break;
    }
  case 2:
    dostuff(123); // Now you cannot use i accidentally
}

编辑

更详细地说,switch语句只是goto的一种特别奇特的类型。下面是一段类似的代码,显示了同样的问题,但使用了goto而不是switch

int main() {
    if(rand() % 2) // Toss a coin
        goto end;

    int i = 42;

  end:
    // We either skipped the declaration of i or not,
    // but either way the variable i exists here, because
    // variable scopes are resolved at compile time.
    // Whether the *initialization* code was run, though,
    // depends on whether rand returned 0 or 1.
    std::cout << i;
}

这篇关于错误:跳转到SWITCH语句中的CASE标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆