简体   繁体   中英

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

With <stdlib.h> included the following code gives the output of 123.34 .

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

But without <stdlib.h> it produces the output of 33.000000.

What is the role of <stdlib.h> here and why did the value 33.00000 occur when it is nowhere in the code?

You must take a look at the warning generated by the compiler.

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

This still yields result, which is not deterministic in any way because the return type expected is float , whereas without the header inclusion, the default is assumed to be int .

If you look into the stdlib header file , there is a declaration,

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

With #include<stdlib.h> , we provide this declaration. When missed, compiler assumes to be returning int , and hence the result is not deterministic. With my system, it produced 0.00000000 as the output, whereas with the necessary inclusions, I got 123.339996 as the output.

As a precaution, make a habit of always compiling the code with -Wall option (Assuming that you are using gcc), or better yet, -Werror option.

The <stdlib.h> header tells the compiler that strtof() returns a float() ; in its absence, the compiler is forced to assume it returns an int . Modern C compilers (GCC 5 and above) complain about the absence of a declaration for strtof() and/or a conflict with its internal memorized declaration for strtof() .

If you omit <stdlib.h> , your code is unacceptable in C99 and C11 because you didn't declare strtof() before using it. Since you omit <stdio.h> , it is invalid in C90, let alone C99 or C11. You must declare variadic functions such as printf() before using them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM