Why 256 for a signed char is undefined in C++

后端 未结 6 468
Happy的楠姐
Happy的楠姐 2020-12-20 03:30

Reading the C++ Primer 5th edition book, I noticed that a signed char with a value of 256 is undefined. I decided to try that, and I saw that

6条回答
  •  情书的邮戳
    2020-12-20 04:06

    @Pubby I don't know if the C/C++ standards have defined the behavior when signed integer overflows, but gcc seems not always treat (x < x + 1) as true. the "<" operator takes signed int as operand, so x < x + 1 --> (int)x < (int)x + (int)1

    the following code produces output: 1 0 0 0 (32bit Linux + gcc)

    signed char c1, c2; 
    signed int i1, i2; 
    
    c1 = 127;
    c2 = c1 + 1;
    
    i1 = 2147483647;
    i2 = i1 + 1;
    
    printf("%d %d\n", c1 < c1 + 1, c1 < c2);
    printf("%d %d\n", i1 < i1 + 1, i1 < i2);
    

提交回复
热议问题