Error: Jump to case label in switch statement(错误:跳转到SWITCH语句中的CASE标签)
本文介绍了错误:跳转到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标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:错误:跳转到SWITCH语句中的CASE标签
基础教程推荐
猜你喜欢
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
