printf displays something weird

后端 未结 5 1314
刺人心
刺人心 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.

    0 讨论(0)
  • 2020-12-06 19:32

    A float is stored in memory in a special format, it's not just a number and some decimal places see How to represent FLOAT number in memory in C

    0 讨论(0)
  • 2020-12-06 19:51

    You need to know how printf works. The caller puts all the arguments on the stack. As it parses through the fmt string, the first time it sees a %d it picks the first 4-byte word on the stack and prints it as an integer. The second time it sees a %d, it picks the next 4-byte word. What you're seeing is the raw float bytes being displayed as two integers.

    0 讨论(0)
  • 2020-12-06 19:56

    printf doesn't just use the format codes to decide how to print its arguments. It uses them to decide how to access its arguments (it uses va_arg internally). Because of this, when you give the wrong format code for the first argument (%d instead of %f) you don't just mess up the printing of the first argument, you make it look in the wrong place for all subsequent arguments. That's why you're getting nonsense for the second argument.

    0 讨论(0)
  • 2020-12-06 19:56

    Is it signed or unsigned?

    Use this as a reference: http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/FUNCTIONS/format.html

    0 讨论(0)
提交回复
热议问题