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标签


猜你喜欢
- DoEvents 等效于 C++? 2021-01-01
- XML Schema 到 C++ 类 2022-01-01
- GDB 不显示函数名 2022-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 将 hdc 内容复制到位图 2022-09-04
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01