strange behavior of scanf for short int

后端 未结 5 2035
余生分开走
余生分开走 2020-12-11 10:25

the code is as follows:

#include 
main()
{
    int m=123;
    int n = 1234;
    short int a;
    a=~0;
          


        
5条回答
  •  情书的邮戳
    2020-12-11 10:58

    You are correct, %d expects and writes an int. If you enter a value less than 65535, it fits in the bytes outside short, so you see 0 when you print a back. I tried reading a short and printing it back; I entered 65536123, and got 123, which makes perfect sense (65536 occupies precisely 16 bits; you see the remaining 123 through the two bytes of the short). This behavior is dangerous, because the other two bytes of the short end up in a "variable next door" to the short, which is very, very bad. I hope this should convince you not to do it.

    P.S. To read a short with scanf, declare a temporary int variable, read the value into it using scanf, and then cast it to short.

提交回复
热议问题