无法在 switch case 中声明变量

yok*_*232 5 c label declaration switch-statement

#include<stdio.h>

void main()
{
    int a = 4;
    switch (a)
    {
        case 4:
            int res = 1;
            printf("%d",res);
        break;

    }
}
Run Code Online (Sandbox Code Playgroud)

当我用 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;
Run Code Online (Sandbox Code Playgroud)

但是当我添加时;case 4:;我可以编译我的代码。

有什么问题,为什么要;解决这个问题?

Vla*_*cow 8

与 C++ 相反,在 C 中声明不是语句,标签只能在语句之前。

在标签后放置一个空语句

case 4:;
Run Code Online (Sandbox Code Playgroud)

你让标签现在不在声明之前。

另一种方法是在标签后使用复合语句,并将声明放在复合语句中,如

    case 4:
    {  
        int res = 1;
        printf("%d",res);
        break;
    }
Run Code Online (Sandbox Code Playgroud)


Mik*_*CAT 6

问题出在您的错误消息中:标签只能附加到语句并且声明不是语句。

看到N1570 6.8.2 Compound statement,有declaration和分别statement列举的,暗示它们是不同的东西。

Syntax
1     compound-statement:
          { block-item-listopt }

      block-item-list:
          block-item
          block-item-list block-item

      block-item:
          declaration
          statement
Run Code Online (Sandbox Code Playgroud)

;case 4:;一个空语句,这是一个声明(在N1570 6.8.3表达及空语句所定义的),并且因此它是允许的。