c - 隐式声明是否应该返回错误

标签 c gcc

考虑下面的测试程序

#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/

相关文章:

C 中使用 const void * 参数调用函数

c - 搜索结构数组

gcc - 关于 GCC 链接器的问题

c - ANSI C (ISO C90) : Can scanf read/accept an unsigned char?

c++ - 将 AVX 与 GCC 一起使用 - 缺少 avxintrin.h

c - 在C代码中通过数组添加两个大数

c - 在 ANSI C 中,如何制作计时器?

c - 读取 .bin 文件的某些部分(例如从 11 日到 23 日): hex into int, 字符串。 C

c - GCC - 限制内的 Signed Long 会在编译期间导致警告

linux - 编译时出现 undefined reference 错误