不包括stdlib.h不会产生任何编译错误!

Bal*_*ala 4 c gcc std atof

希望这是一个非常简单的问题.以下是我的C pgm(test.c).

#include <stdio.h>
//#include <stdlib.h>

int main (int argc, char *argv[]) {
    int intValue = atoi("1");
    double doubleValue = atof("2");
    fprintf(stdout,"The intValue is %d and the doubleValue is %g\n", intValue, doubleValue);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意,我正在使用stdlib.h中的atoi()和atof(),但我没有包含该头文件.我编译pgm(gcc test.c)并且没有编译错误!

我运行pgm(./a.out),这是输出,这是错误的.

The intValue is 1 and the doubleValue is 0
Run Code Online (Sandbox Code Playgroud)

现在我包含stdlib.h(通过删除#include之前的注释)并重新编译它并再次运行它.这次我得到了正确的输出:

The intValue is 1 and the doubleValue is 2
Run Code Online (Sandbox Code Playgroud)

为什么编译器没有抱怨不包含stdlib.h并且仍然让我使用atoi(),atof()函数?

我的gcc信息:

$ gcc --version
gcc (GCC) 4.1.2 20070925 (Red Hat 4.1.2-27)
Run Code Online (Sandbox Code Playgroud)

任何想法赞赏!

zwo*_*wol 12

由于历史原因 - 特别是与非常旧的C程序(C89之前版本)的兼容性- 使用未首先声明它的函数只会引发GCC的警告,而不是错误.但是假定这种函数的返回类型int不是double,这就是程序错误执行的原因.

如果-Wall在命令行上使用,则会获得诊断:

$ gcc -Wall test.c
test.c: In function ‘main’:
test.c:5: warning: implicit declaration of function ‘atoi’
test.c:6: warning: implicit declaration of function ‘atof’
Run Code Online (Sandbox Code Playgroud)

你应该-Wall总是使用.对新代码等非常实用的警告选项-Wextra,-Wstrict-prototypes,-Wmissing-prototypes,-pedantic,和-Wwrite-strings,但相比-Wall他们有更高的假阳性率.

切线:从不使用atoi也不会atof隐藏输入错误.使用strtolstrtod替代.