-1
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?

lllle00
  • 11
  • 2
  • 1
    Please include the output in your question as text, formatted as code, not as a link to an image on another site. And you forgot the required `#include `. – Keith Thompson May 28 '21 at 02:51
  • To get the desired output, you need casts to the types that the corresponding format specifiers expect: `printf("int x=%d, float x=%f, y=%f, y=%d\n", x, (double)x, y, (int)y);` Note the promotion of `float` to `double` for the fourth argument (`y`) is automatic. – Nate Eldredge May 28 '21 at 03:12
  • [What happens when I use the wrong format specifier?](https://stackoverflow.com/q/16864552/995714) UB happens – phuclv May 28 '21 at 04:18

1 Answers1

2

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.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • 1
    On platforms like x86-64 where floating point args are passed in a separate set of registers than integers, you will get a floating-point value that is totally unrelated to the integers you passed. – Nate Eldredge May 28 '21 at 03:11