在IF语句中定义的未定义变量出错

 努力学习的PHP程序员 发布于 2023-02-11 13:28

在尝试编译以下代码片段时:

#include 
#include 

void change_a(int * a) {
    *a = 1;
    return;
}

void main(void) {
    int a = 0;
    change_a(&a);
    if (a) {
        time_t start = time(NULL);
    }
/* do something that never mentions a */

    if (a) {
        time_t end = time(NULL);
       printf("Time spent = %ld\n", (int) end - start);
    }
}

GCC声明该行中的start变量未定义printf:

$ gcc --version
gcc (Debian 4.8.2-1) 4.8.2
[SNIP]
$ gcc -o test.bin test.c 
test.c: In function ‘main’:
test.c:24:44: error: ‘start’ undeclared (first use in this function)
   printf("Time spent = %ld\n", (int) end - start);

另一方面,当将main函数更改为:时,它可以编译并正常工作:

void main(void) {
    int a = 0;
    time_t start = 0;

    change_a(&a);
    if (a) {
        start = time(NULL);
    }
    ...

问题1

我做错了什么,或者编译器做了一些我不知道的有趣的事情?

我认为可能是编译器过于聪明并且优化了这段代码或者在其启发式或其他方面出现故障.但每隔一段时间我"发现编译器错误"总是让我错过了一些非常明显的错误.

因此,在我指责其他聪明人不那么聪明之前,我宁愿聪明的人检查一下.特别是在没有优化的情况下也会发生问题:

$ gcc -O0 -o test.bin test.c 
test.c: In function ‘main’:
test.c:24:44: error: ‘start’ undeclared (first use in this function)
   printf("Time spent = %ld\n", (int) end - start);
                                            ^
test.c:24:44: note: each undeclared identifier is reported only once for each function it appears in

问题2

我还想知道是否有更好的方法来避免编译器错误(如果不是最后一个代码片段中的解决方法).如果我的代码错误(因为响应将包含"正确的"代码),这很明显,但我也想知道如何在某人修复GCC中的(涉嫌)错误时避免错误.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有