printf displays something weird

后端 未结 5 1342
刺人心
刺人心 2020-12-06 19:26

There is such code:

#include 

int main() {
  float d = 1.0;
  int i = 2;
  printf(\"%d %d\", d, i);
  getchar();
  return 0;
}
5条回答
  •  渐次进展
    2020-12-06 19:29

    Since you specified %d instead of %f, what you're really seeing is the binary representation of d as 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:

    float gets promoted to double on the stack. Type double is (in this case) 8 bytes long. However, since your printf specifies two integers (both 4 bytes in this case), you are seeing the binary representations of 1.0 as a type double. The 2 isn't printed because it is beyond the 8 bytes that your printf expects.

提交回复
热议问题