Problem with printf()

Casper H.S. Dik dik at uva.UUCP
Fri Oct 7 00:00:28 AEST 1988


In article <504 at imec.UUCP> croes at imec.UUCP (Kris Croes) writes:
>Hello NetLand, 
>
>May I introduce to you...
>A little program containing a big problem.
>  main()
>  {
>  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 ?
>
No wonder, float arguments in C are converted to doubles before being passed
to functions. So printf expects sizeof(int)+sizeof(double) bytes but gets
sizeof(double)+sizeof(double). Since sizeof(double) > sizeof(float) this
results in printf interpreting garbage as data, thus resulting in
GIGO (Garbage In, Gospel Out).

If you had read the entire printf manual, you would have been put on the
right track by the explanation of %f '... converts the float or double 
argument ...'.

BTW you posted to the wrong news group. Printf is a standard C function
and the proper newsgroup would be comp.lang.c.

____________________________________________________________________________
Casper H.S. Dik
Student
University of Amsterdam     |		      dik at uva.uucp
The Netherlands             |                 ...!uunet!mcvax!uva!dik
____________________________________________________________________________
Casper H.S. Dik
University of Amsterdam     |		      dik at uva.uucp
The Netherlands             |                 ...!uunet!mcvax!uva!dik



More information about the Comp.unix.wizards mailing list