Saturday 9 November 2013

Always include the header files when using some standard C libraries

Yesterday, I was working on a C code of mine when I  came across a very peculiar problem. I even wrote a test code to regenerate the problem I was facing.

int main()
{
    char str[10]="3.5";
    printf("%lf",atof(str));
    return 0;
}
This is a simple code I am testing at ideone.com. I am getting the output as
-0.371627
I was out of reason why the function atof was failing. After little research I found out that I have not included the header file 'stdlib.h'. GCC compiler only issue a warning when you don't include a standard header file but there is a catch. Without the header file, compiler assumes the return type of the functions used to be of type 'int'. This leads to the failure of above code as it was returning 'float'. So, when you are writing code in GCC, always include all the required header files and do not ignore the warnings.

No comments:

Post a Comment