There is such code:
#include <stdio.h>
int main() {
float d = 1.0;
int i = 2;
printf("%d %d", d, i);
getchar();
return 0;
}
And the output is:
0 1072693248
I know that there is error in printf and first %d should be replaced with %f. But why variable i is printed wrong (1072693248 instead of 2)?
Since you specified
%dinstead of%f, what you’re really seeing is the binary representation ofdas an integer.Also, since the datatypes don’t match, the code actually has undefined behavior.
EDIT:
Now to explain why you don’t see the
2:floatgets promoted todoubleon the stack. Typedoubleis (in this case) 8 bytes long. However, since yourprintfspecifies two integers (both 4 bytes in this case), you are seeing the binary representations of1.0as a typedouble. The 2 isn’t printed because it is beyond the 8 bytes that yourprintfexpects.