【问题标题】:Attribution in first line on switch statement make a error in gccswitch 语句第一行的归属在 gcc 中出错
【发布时间】:2014-08-18 00:03:30
【问题描述】:

为什么除非我删除评论,否则代码不起作用?

#include <stdio.h>

int main(){
    int num = 5;
    switch(num){
        case 5:
            //printf("");
            int another = 1;
            printf("%d", num+another);
            break;
    }
}

gcc 返回错误:

prog.c: In function ‘main’:
prog.c:7:13: error: a label can only be part of a statement and a declaration is not a statement

谢谢。

【问题讨论】:

标签: c gcc switch-statement


【解决方案1】:

这里概述了原因:Why can't variables be declared in a switch statement?

作为一种解决方法,您可以这样做:

#include <stdio.h>

int main(){
    int num = 5;
    switch(num){
        case 5:;
            //printf("");
            int another = 1;
            printf("%d", num+another);
            break;
    }
}

在大小写之后包含一个分号作为解决方法。欺骗编译器认为后面是语句而不是声明。取自here

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2021-07-18
    相关资源
    最近更新 更多