无法在 switch case 中声明变量

标签 c switch-statement label declaration

这个问题在这里已经有了答案:





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/

相关文章:

android:onClick xml 未执行

c - window : two threads handling messages?

c - 快速读取大于c中内存的文件

c++ - 如何在 C++ 中的 switch 中使用 bool 表达式

matlab - Matlab 开关/案例中的空语句?

Swift:文本标签未更新

分割数据中带有标签间隙的 R 箱线图

c - 定义具有特定对齐方式的自动变量的优雅方式

C 中的凯撒密码适用于下层而不是上层

c# - 使用 MYSQL 数据库数据的 Switch 语句 C#