知乎讨论
- 请教switch内部的变量定义问题?
C版本
#include<stdio.h>
int main()
{
int a=1;
switch(a)
{
case 1:
int b=20;
printf("b is %d\n",b);
break;
default:printf("b is %d\n",b);
break;
}
return 0;
}
gcc下编译报错,信息如下:
error: a label can only be part of a statement and a declaration is
not a statement
int b=20;
^
两个知识点:
1. 标签只能是语句的一部分;
2. 声明不是语句。
不知道,一点也不知道。
C++版本
#include <string>
#include<iostream>
using namespace std;
int main()
{
int a=1;
switch(a)
{
string str;
case 1:
cout << "str is " << str << endl;
break;
default:
cout << "str is " << str << endl;
break;
}
return 0;
}
g++下编译报错,信息如下:
16.cpp: In function ‘int main()’:
16.cpp:17:8: error: jump to case label [-fpermissive] case 1:
^
16.cpp:16:10: note: crosses initialization of ‘std::__cxx11::string str’ string str;
^
16.cpp:20:3: error: jump to case label [-fpermissive] default: ^
16.cpp:16:10: note: crosses initialization of ‘std::__cxx11::string str’ string str;
^
如果把string str;语句放在case 1:下一行,g++编译会报错:
16.cpp: In function ‘int main()’:
16.cpp:20:3: error: jump to case label [-fpermissive] default: ^
16.cpp:17:11: note: crosses initialization of ‘std::__cxx11::string str’
string str;
^
有关博文:
- C语言:error: a label can only be part of a statement and a declaration is not a statement|
2021-05-13 更新
开头的链接里面,回答好像不全了,下面这个好像是全的
- 转:switch内部的变量定义问题(goto类似)
另加的:
- Switch-case 内定义变量的问题
- Why can’t variables be declared in a switch statement?