[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: I'm confused: what's with atof?

gobbel@andrew.cmu.edu (Randy Gobbel) writes:
> Ok, I know the whole world can't have gone crazy overnight, so it must
> be me.  This program:
> #include <stdio.h>
> int main(int argc, char **argv)
> {
>   char *sxxx = "1";
>   int xxx = atoi(sxxx);
>   char *sfoo = "1.0";
>   double foo = atof(sfoo);
>   double bar = 1.0;
>   double zot = foo + bar;
>         printf("xxx(%s) = %d, foo(%s) = %f, bar = %f, foo+bar = %f\n",
> sxxx, xxx, sfoo, foo, bar, zot);
> }
> Does this:
> xxx(1) = 1, foo(1.0) = 2147482232.000000, bar = 1.000000, foo+bar =
> 2147482233.000000

A couple of problems:
 float and double are not always interchangeable
 %f and %g cannot are not always interchangeable
 default conversions on vararg functions (printf) can promote floats to
  doubles without telling you
 compiling your code with -Wall reveals that atof() has no prototype. In the
  absence of prototypes, functions return an int. Since you're assigning an
  int to a double, some weird conversion takes place. When atof() returns the
  binary float representation of 1.0, that blob is then treated as if it were
  the binary representation of an 'int', and the weird conversion gets really

Adding #include <stdlib.h> and being careful to keep float/%f and double/%g
in pairs makes my Solaris box print out the right thing. Otherwise I get
strange results like yours.

Is the emacs source file that uses this function pulling in a proper
prototype? Some of that code might be old enough (or intended to be compiled
on sufficiently old systems) that it might avoid using -Wall just because of
the noise. The prototype for atof() could have moved from one glibc to another
(maybe), also I recall problems on SunOS in which the gcc-fixed C library
headers didn't actually define any prototypes unless something like
__USE_FIXED_PROTOTYPES__ was turned on, which generally needed to be done in
gcc's spec file, which would be an example of a thing that would vary from
one version of gcc to the next.

Just throwing out some ideas..

Reply to: