strange behavior of scanf for short int

后端 未结 5 2019
余生分开走
余生分开走 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 11:18

    If you had actually used variable n, then it would probably have been the one that got clobbered, rather than m. Since you didn't use n, the compiler optimized it away, and that means that it was m that got clobbered by scanf() writing 4 bytes (because it was told that it got a pointer to a (4-byte) integer) instead of the 2 bytes. This depends on quite a lot of details of your hardware, such as endian-ness and alignment (if int had to be aligned on a 4-byte boundary, you wouldn't see the problem; I guess you are on an Intel machine rather than, say, PowerPC or SPARC).

    Don't fib to your compiler - even accidentally. It will get its own back.

提交回复
热议问题