a label can only be part of a statement and a declaration is not a statement

在研究U-Boot源码时发现cread_line函数中的一处编译错误,该错误源于变量声明位置不当。通过调整代码结构,使用花括号包裹整个case块,成功解决了编译器报错问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在查阅u-boot代码时,发现一个奇怪的地方。记录下来,以备后续追溯。


u-boot代码的main.c模块中,有一个cread_line函数,其中有一段话是这样的:

case '\t':
    int num2, col;

    /* do not autocomplete when in the middle */
    if (num < eol_num) {
        getcmd_cbeep();
        break;
    }

    buf[num] = '\0';
    col = strlen(prompt) + eol_num;
    num2 = num;
    if (cmd_auto_complete(prompt, buf, &num2, &col)) {
        col = num2 - num;
        num += col;
        eol_num += col;
    }
    break;

编译时报错:

main.c: In function 'cread_line':
main.c:863: error: a label can only be part of a statement and a declaration is not a statement
main.c:891: error: a label can only be part of a statement and a declaration is not a statement
make[1]: *** [main.o] 错误 1

百度了一下,http://www.cnblogs.com/lovevivi/archive/2012/11/06/2756374.html中说到:

此块代码不能再声明变量,如果你声明变量就会报错,除非用括号括起来,这是编译器的问题,也可以说是C语言的规定。写代码的时候注意就成了。就像C语言再声明的时候不能赋值一样。

所以,最简单的解决办法就是,将case中的代码用括号括起来:

case '\t':
    {
        int num2, col;

        /* do not autocomplete when in the middle */
        if (num < eol_num) {
            getcmd_cbeep();
            break;
        }

        buf[num] = '\0';
        col = strlen(prompt) + eol_num;
        num2 = num;
        if (cmd_auto_complete(prompt, buf, &num2, &col)) {
            col = num2 - num;
            num += col;
            eol_num += col;
    }
    break;

搞定!收工!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值