这个问题在这里已经有了答案:
Why can't variables be declared in a switch statement?
(23 个回答)
去年关闭。
#include<stdio.h>
void main()
{
int a = 4;
switch (a)
{
case 4:
int res = 1;
printf("%d",res);
break;
}
}
当我用 gcc 编译这段代码时,我得到了错误root@ubuntu:/home/ubuntu# gcc test.c -o t
test.c: In function ‘main’:
test.c:9:4: error: a label can only be part of a statement and a declaration is not a statement
int res = 1;
但是当我添加 ;
喜欢 case 4:;
我可以编译我的代码。是什么问题以及为什么
;
解决这个问题?
最佳答案
与 C++ 相反,在 C 中声明不是语句,标签只能在语句之前。
在标签后放置一个空语句
case 4:;
你让标签现在不在声明之前。另一种方法是在标签后使用复合语句,并将声明放在复合语句中,如
case 4:
{
int res = 1;
printf("%d",res);
break;
}
关于无法在 switch case 中声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64120549/