不包括stdlib.h中不​​会产生任何的编译器错误! [英] Not including stdlib.h does not produce any compiler error!

查看:285
本文介绍了不包括stdlib.h中不​​会产生任何的编译器错误!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望这是一个很简单的问题。继在C PGM(test.c的)我有。

Hopefully this is a very simple question. Following is the C pgm (test.c) I have.

#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;
}

请注意,我用的atoi()和stdlib.h中ATOF(),但我不包括头文件。我编译PGM(GCC test.c的),并没有得到编译器错误!

Note that I am using atoi() and atof() from stdlib.h, but I do not include that header file. I compile the pgm (gcc test.c) and get no compiler error!

我运行PGM(./a.out)这里是输出,这是不对的。

I run the pgm (./a.out) and here is the output, which is wrong.

The intValue is 1 and the doubleValue is 0

现在我有stdlib.h中(通过删除的#include之前的意见),并重新编译,并再次运行。这一次,我得到正确的输出:

Now I include stdlib.h (by removing the comments before the #include) and recompile it and run it again. This time I get the right output:

The intValue is 1 and the doubleValue is 2

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

How come the compiler did not complain about not including the stdlib.h and still let me use the atoi(), atof() functions?

我的gcc的信息:

$ gcc --version
gcc (GCC) 4.1.2 20070925 (Red Hat 4.1.2-27)

有什么想法AP preciated!

Any thoughts appreciated!

推荐答案

由于历史的原因 - 尤其是兼容性的非常的旧的C程序(pre-C89) - 使用函数而不必首先声明它只是引发从GCC的警告,而不是一个错误。但这样的函数的返回类型被假定为 INT ,而不是双击,这就是为什么在程序执行不正确

For historical reasons -- specifically, compatibility with very old C programs (pre-C89) -- using a function without having declared it first only provokes a warning from GCC, not an error. But the return type of such a function is assumed to be int, not double, which is why the program executes incorrectly.

如果您使用 -Wall 在命令行中,你会得到一个诊断:

If you use -Wall on the command line, you get a diagnostic:

$ 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’

您应该使用 -Wall 基本上始终。新的code。其他非常有用的警告选项为 -Wextra -Wstrict的原型 -Wmissing的原型 -pedantic -Wwrite串,但相比于 -Wall ,他们有更高的假阳性率。

You should use -Wall basically always. Other very useful warning options for new code are -Wextra, -Wstrict-prototypes, -Wmissing-prototypes, -pedantic, and -Wwrite-strings, but compared to -Wall they have much higher false positive rates.

切向:从来不使用的atoi 也不 ATOF ,他们隐藏输入错误。使用与strtol 的strtod 代替。

Tangentially: never use atoi nor atof, they hide input errors. Use strtol and strtod instead.

这篇关于不包括stdlib.h中不​​会产生任何的编译器错误!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆