c - printfing a float using %d -
i wrote program intentional error in printf
#include <stdio.h> int main() { double foo = 2.54f; printf("-> %d\n", foo); }
and after running few times ouputs:
-> 1180400440
-> 1754655672
-> 1596232744
-> -905631720
-> 202675976
-> -1580281720
-> 1020283160
-> 929827960
my question is, why output different number every time run program?
because on platform, double
s , int
s passed functions differently. normally, double
s passed in floating-point registers, while int
s passed in general purpose registers. (up limit, of course; run out of registers , if there many arguments, remaining ones passed on stack.)
when tell printf
expect int
, looks int
expects find int
s. gpr has not been set particular value, because when called printf
, called double
put floating point register.
you don't need know that, although might interesting. it's undefined behaviour (ub) lie printf
types of arguments provide, , compilers warn (at least if provide -wall
command-line option or equivalent). ub means pretty might happen, including, example, premature termination of program or random data being used. make sure ask compiler give warnings, , make sure fix them.
Comments
Post a Comment