Re: The printf format

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

 



On 14/01/13 12:29, GHui wrote:
> I code the following code.
> --------------------------
> #include <stdio.h>
> int main(int argc,char **argv)
> {
>     float f[2]={4.0, 37.4};
>     printf("%.2f    %.2f\n",f[0],f[1]);
>     printf("%d    %.2f\n",f[0],f[1]);
> }
>
> And it output is following.
> -------------------------
> 4.00    37.40
> -1    4.00
>
> I confuse that f[1] is 4.00 at the second line.
> Any help will be appreciated.
>
> --GHui
In the second case you are pushing two floats to the stack.
Then printf tries to pop an integer and a float.
You need to take into account that in variable-length arguments,
floats get promoted into double, so even if int and float are of the
same size in your system (something on which you can't rely), printf
is actually poping a double (probably not the size of your int).
When you lie in the arguments you pass, you can get all kind of
garbage. Specially when floats and doubles are, since they are
sometimes passed in special registers (depending on the ABI).
In this case, I think that the 4.0 you are getting is f[0] passed in
a special register, and you would have been shown 37.40 if
adding a second %.2f. But those are internals of the ABI.
Respect the parameter formats and all will be good.


If you want to print f[0] as an integer use:

printf("%d    %.2f\n",(int)f[0],f[1]);


This kind of bug is warned by gcc when using -Wformat (included in -Wall).



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux