If char c = 0x80, why does printf(“%d\n”, c << 1) output -256?

前端 未结 5 518
一整个雨季
一整个雨季 2021-01-05 21:27
#include
int main(void)
{
  char c = 0x80;
  printf(\"%d\\n\", c << 1);
  return 0;
}

The output is -256 in this

5条回答
  •  失恋的感觉
    2021-01-05 21:45

    I wonder why your compiler do not complain with a warning that 0x80 does not fit in char, which on your platform can represent only values from -0x80 to 0x7F.

    Try this piece of code:

     #include 
     #include 
     #include 
    
     int main() {
          printf("char can represent values from %d to %d.\n", CHAR_MIN, CHAR_MAX);
          return EXIT_SUCCESS;
     }
    

    Your situation is called OVERFLOW.

提交回复
热议问题