Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

atof() is returning ambiguous value

Tags:

c

atof

I am trying to convert a character array into double in c using atof and receiving ambiguous output.

printf("%lf\n",atof("5"));

prints

262144.000000

I am stunned. Can somebody explain me where am I going wrong?

like image 769
alDiablo Avatar asked Dec 16 '22 03:12

alDiablo


1 Answers

Make sure you have included the headers for both atof and printf. Without prototypes the compiler will assume they return int values. When that happens the results are undefined, since that doesn't match atof's actual return type of double.

#include <stdio.h>
#include <stdlib.h>

No prototypes

$ cat test.c
int main(void)
{
    printf("%lf\n", atof("5"));
    return 0;
}

$ gcc -Wall -o test test.c
test.c: In function ‘main’:
test.c:3:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
test.c:3:5: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
test.c:3:5: warning: implicit declaration of function ‘atof’ [-Wimplicit-function-declaration]
test.c:3:5: warning: format ‘%lf’ expects argument of type ‘double’, but argument 2 has type ‘int’ [-Wformat]

$ ./test
0.000000

Prototypes

$ cat test.c
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("%lf\n", atof("5"));
    return 0;
}

$ gcc -Wall -o test test.c

$ ./test
5.000000

Lesson: Pay attention to your compiler's warnings.

like image 72
John Kugelman Avatar answered Jan 27 '23 19:01

John Kugelman