Reputation: 527
I need to pass a double to my program, but the following does not work:
int main(int argc, char *argv[]) {
double ddd;
ddd=atof(argv[1]);
printf("%f\n", ddd);
return 0;
}
If I run my program as ./myprog 3.14
it still prints 0.000000
.
Can somebody please help?
Upvotes: 10
Views: 15912
Reputation: 2351
In C you don't require to declare a function before you use it (in contrast with C++), and if that happens (no prototype), compiler makes some assumptions about that function. One of those assumptions is that it returns int
. There's no error, atof()
works, but it works incorrectly. It typically get whatever value happens to be in the register where int
is supposed to be returned (it is 0 in your case, but it can be something else).
P.S. atof()
and atoi()
hide input errors (which you can always see by adding option -Wall to your gcc compiler call: gcc -Wall test.c
), so most people prefer to use strtol()
and strtod()
instead.
Upvotes: 2
Reputation: 4353
As remyabel indicated, you probably neglected to #include <stdlib.h>
. The reason this matters is that, without having a declaration of atof()
, the C standard mandates that the return value is assumed to be int
. In this case, it's not int
, which means that the actual behavior you observe (getting a return value of 0
) is technically unspecified.
To be clear, without the double
-returning declaration, the line ddd=atof(argv[1])
is treated as a call to an int
-returning function, whose result is then cast to a double
. It is likely the case that the calling conventions on the particular system you're on specify that int
s and double
s get returned in different registers, so the 0
is likely just to be whatever happened to be in that particular register, while the double
return value is languishing, unobserved.
Upvotes: 4
Reputation:
My guess is you forgot to include #include <stdlib.h>
. If this is the case, gcc
will issue the following warning:
warning: implicit declaration of function 'atof' [-Wimplicit-function-declaration]
And give the exact output you provided: 0.000000
.
Upvotes: 9