为什么 strtof() 的这种行为会随着 stdlib.h 的变化而变化?

why is this behaviour of strtof() changes with respect to the change in stdlib.h?

包含 <stdlib.h> 后,以下代码给出了 123.34 的输出。

#include<stdlib.h>  
int main()
{
    char *str="123.34";
    float f= strtof(str,NULL);
    printf("%f",f);
}

但如果没有 <stdlib.h>,它会产生 33.000000 的输出。

这里<stdlib.h>的作用是什么,为什么代码中没有出现值33.00000?

<stdlib.h> header 告诉编译器 strtof() returns a float();如果没有,编译器将被迫假设它 returns 和 int。现代 C 编译器(GCC 5 及更高版本)抱怨缺少 strtof() and/or 的声明与其内部记忆的 strtof().

声明冲突

如果您省略 <stdlib.h>,您的代码在 C99 和 C11 中是不可接受的,因为您在使用它之前没有声明 strtof()。因为你省略了<stdio.h>,所以在C90中是无效的,更不用说C99或C11了。在使用它们之前,您必须声明可变参数函数,例如 printf()

你必须看看编译器产生的警告。

warning: implicit declaration of function 'strtof' [-Wimplicit-function-declaration]

这仍然会产生结果,这在任何方面都不是确定性的,因为预期的 return 类型是 float,而如果没有 header 包含,则假定默认为 int.

如果你查看 stdlib header file,有一个声明,

float strtof(const char *restrict, char **restrict);

使用#include<stdlib.h>,我们提供此声明。错过时,编译器假定 returning int,因此结果不确定。 在我的系统中,它产生了 0.00000000 作为输出,而在必要的包含之后,我得到了 123.339996 作为输出。

作为预防措施,养成总是使用 -Wall 选项编译代码的习惯(假设您使用的是 gcc),或者更好的是 -Werror 选项。