atof函数在不包含头文件stdlib.h的情况下也能编译运行,但是转换结果是错误的,为什么

来源:互联网 发布:网吧计费系统c语言 编辑:程序博客网 时间:2024/04/29 05:29

c - Not including stdlib.h does not produce any compiler error!


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.


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’


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.


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


参考stackoverflow

http://stackoverflow.com/questions/4800102/not-including-stdlib-h-does-not-produce-any-compiler-error


翻译如下:

由于一下历史性的原因,为了兼容老的C程序(早于C89)在使用一个未申明的函数时只会获得一个警告,而不是编译错误。 但是若使用此函数返回值的话,他将被认为是int类型而非double。这也就是为何他会导致程序运行错误。


如果你开启了gcc的 -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’

提示你隐式申明的某些函数。

因此你应该总是打开gcc的 -Wall 选项。 其他有用的警告选项比如  -Wextra, Wstrict-prototypes, -Wmissing-prototypes, -pedantic, 和  -Wwrite-strings. 但是他们和-Wall比起来要严格得多。


另外推荐,不要使用atoi和atof 因为他们并不能处理输入错误  ,使用 strtol 或者  strtod.

0 0
原创粉丝点击