2018-03-08 [转] goto 引起的声明错误

goto 引起的 "a label can only be part of a statement and a declaration is not a statement" 错误

之前写代码的时候用了一个goto语句,结果编译提示a label can only be part of a statement and a declaration is not a statement,一开始并不理解,因为之前一直没碰到过类似的错误,google了一下也找不到满意的答案,最后又仔细琢磨了这个错误,并对比代码,终于发现了问题的症结所在:原来是由于我在label之后进行变量的声明而导致的错误,label只能是语句的一部分,而变量的声明并不是一个语句。

原来代码的粗略流程如下:

    if (!zmhss_fsready()) {
        goto defaul_init;
    }
    // ........

defaul_init:

    struct rlimit     rlmt;  // 在此声明变量是致命的

    if (ccf->rlimit_nofile != -1) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_nofile;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_nofile;

        if (setrlimit(RLIMIT_NOFILE, &rlmt) == -1) {
            exit(2);
        }
    }

就是上面这一句 struct rlimit rlmt; 才最终导致了编译过程出现的错误提示,解决的方法是将这句 struct rlimit rlmt; 对变量的声明移到label之前即可,即修改后代码结构体如下:

    struct rlimit rlmt;
    
    if (!zmhss_fsready()) {
        goto defaul_init;
    }
    // ..............

经过上述修改后,问题得以解决。从这个问题可以做一个引申,即在写代码的时候,变量的声明不应该出现在label之后,比如switch语句中的case结构也可能会遇到类似的问题。

[reference]

[1] weiyuefei. 错误“a label can only be part of a statement and a declaration is not a statement”解决方法[M]. (2014年06月17日 16:41:24) http://blog.csdn.net/weiyuefei/article/details/31775043

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容