DSUK
DSUK

Reputation: 284

printfing a float using %d

I wrote this program with the intentional error in printf

#include <stdio.h>

int main()
{
        double foo = 2.54f;
        printf("-> %d\n", foo);
}

and after running it a few times it ouputs:

-> 1180400440

-> 1754655672

-> 1596232744

-> -905631720

-> 202675976

-> -1580281720

-> 1020283160

-> 929827960

My question is, why does it output a different number every time I run the program?

Upvotes: 1

Views: 170

Answers (2)

rici
rici

Reputation: 241671

Because on your platform, doubles and ints are passed to functions differently. Normally, doubles are passed in floating-point registers, while ints are passed in general purpose registers. (Up to some limit, of course; eventually you run out of registers and if there are too many arguments, the remaining ones will be passed on the stack.)

When you tell printf to expect an int, it looks for the int where it expects to find ints. But that GPR has not been set to any particular value, because when you called printf, you called it with a double which was put into a floating point register.

You don't really need to know that, although it might be interesting. It's actually undefined behaviour (UB) to lie to printf about the types of the arguments you provide, and most compilers will warn you about that (at least if you provide the -Wall command-line option or equivalent). UB means that pretty well anything might happen, including, for example, premature termination of the program or completely random data being used. So make sure you ask the compiler to give you warnings, and make sure you fix them.

Upvotes: 5

ouah
ouah

Reputation: 145829

The error makes your program invokes undefined behavior.

See this C defect report question:

http://www.open-std.org/jtc1/sc22/wg14/docs/rr/dr_083.html

Undefined behavior means everything can happen.

Upvotes: 1

Related Questions