Why the result are so strange

58 Views Asked by At
int main( )
{
   int x = 5;
   float y = 3.1f;
   printf("int x=%d   ,float x=%f    ,y=%f,    y=%d\n", x, x, y, y);  //X86
   return 0;
}

I think the answer are 5 , 5.0 , 3.1 , 3. but the answer is enter image description here

why?

1

There are 1 best solutions below

1
On

The %d format specifier requires an argument of type int, and %f requires an argument of type double (possibly promoted from float). If you pass an argument of the wrong type, the behavior is undefined.

The solution: Don't do that.

(The most likely behavior is that the memory or register containing an int value will be displayed as if it were of type double, but anything could happen.)

For most function calls, passing an int to a function expecting a double argument causes the value to be converted, so 42 becomes 42.0. But since printf is variadic, the expected types are determined by the format string, not the parameter type, so the compiler can't in general know to generate a type conversion.