考虑下面的测试程序
#include<stdio.h>
#include<stdlib.h>
#include <math.h>
int main()
{
double t = nan(NULL);
printf("%g\n",t);
return 0;
}
编译
/usr/local/bin/gcc -lm -o test test.c
输出为预期的 NaN。 但是,如果我输入错误或出错并遗漏了
#include <math.h>
它编译正常,没有错误,没有警告,但输出为 0
如果我使用 -Wall
进行编译,它确实会给出警告 warning: implicit declaration of function `nan' 尽管这种行为似乎比警告更有值(value)。不停止编译有什么意义吗?有没有人有任何关于如何阻止这种在相当大的文件上引起严重头痛的建议?
最佳答案
Should an implicit declaration return an error
是的。隐式声明在 C89 中是“有效的”(但仍然存在问题、令人困惑和不良做法),但在 C99 和 C11 中,它们是被禁止的。
C99,6.5.1.2:
An identifier is a primary expression, provided it has been declared as designating an object (in which case it is an lvalue) or a function (in which case it is a function designator).79
79) Thus, an undeclared identifier is a violation of the syntax.
让您感到困惑的是 GCC 和 clang(鉴于使用的命令行开关,我认为您正在使用其中之一)默认情况下不符合 C 实现,没有额外的严格标志,例如 -Werror -pedantic -pedantic-errors
.
关于c - 隐式声明是否应该返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20884094/