Problem with printf()

Greg Limes limes at ouroborous
Sat Oct 8 05:58:14 AEST 1988


In article <504 at imec.UUCP>, croes at imec (Kris Croes) writes:
>  int i = 17;
>  float f = 17.0;
>
>  printf("%d %f\n",i,i); /*1*/
>  printf("%d %f\n",f,f); /*2*/

>Its output is:
>17 0.000000
>17032 0.000000
>      ^^^^^^^^ Shouldn't this be 17.00000 ?

Nope. You put a floating point number in the arg list, there is no guarantee
that printf, expecting an integer, will do the right thing. Try:

   printf("%d %f\n", i, (float)i);
   printf("%d %f\n", (int)f, f);

I expect that the float is being promoted to a double, which is taking up more
space than an integer. Assuming 32 bit integers, 32 bit floats, and 64 bit
doubles (not unreasonable), and arguments passed in memory, the %d would pick up
the first 32 bits of the double precision 17.0 (==17032), and the %f would pick
up the second 32 bits of the first double and the first 32 bits of the second
double.

In short, "printf" did not screw up your stack. "main" did, by passing badly
typed parameters.
-- 
Greg Limes [limes at sun.com]		semper ubi, sub ubi



More information about the Comp.unix.wizards mailing list