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, doubles , ints passed functions differently. normally, doubles passed in floating-point registers, while ints 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 ints. 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

Popular posts from this blog

php - Magento - Deleted Base url key -

javascript - Tooltipster plugin not firing jquery function when button or any click even occur -

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -