Printf shows something strange

There is a code like this:

#include <stdio.h> int main() { float d = 1.0; int i = 2; printf("%d %d", d, i); getchar(); return 0; } 

And the result:

 0 1072693248 

I know there is an error in printf, and first% d should be replaced with% f. But why is the variable I printed incorrectly (1072693248 instead of 2)?

+6
source share
5 answers

Since you specified %d instead of %f , what you really see is a binary representation of d as an integer.

Also, since the data types do not match, the code does have undefined behavior.

EDIT:

Now, to explain why you do not see 2 :

float gets promoted to double on the stack. The double type (in this case) is 8 bytes. However, since your printf specifies two integers (both 4 bytes in this case), you see the binary representations of 1.0 as a double type. 2 does not print because it exceeds 8 bytes expected by your printf .

+11
source

printf doesn't just use format codes to decide how to print its arguments. He uses them to decide how to access his arguments (he uses va_arg internally). Because of this, when you specify the wrong code format for the first argument ( %d instead of %f ), you will not just ruin the print of the first argument, you will make it look in the wrong place for all subsequent arguments. That is why you are invading the second argument.

+4
source

You need to know how printf works. The caller pushes all arguments onto the stack. When he parses the fmt line, the first time he sees% d, he selects the first 4-byte word on the stack and prints it as an integer. The second time he sees% d, he selects the next 4-byte word. You see that raw floating point bytes are displayed as two integers.

+1
source

The float is stored in memory in a special format, it is not only a number and some decimal places, see How to represent the FLOAT number in memory in C

0
source

Source: https://habr.com/ru/post/897408/


All Articles