Behavior of increment operator at bounds for character type

前端 未结 2 1217
小鲜肉
小鲜肉 2021-01-22 03:17

I wonder how C++ behaves in this case:

char variable = 127;
variable++;

In this case, variable now equals to -128. However did the increment op

相关标签:
2条回答
  • 2021-01-22 03:34

    Plain char can be either signed or unsigned. If the maximum value is 127, then it must be signed in your implementation.

    For unsigned types, "overflow" is well defined, and causes wraparound. For signed types, the behavior on arithmetic overflow is undefined (wraparound is typical, but not required). But that actually doesn't apply in this particular case; instead, the value stored in variable is implementation-defined.

    For types narrower than int, things are a little more complicated. This:

    variable ++;
    

    is equivalent to this:

    variable = variable + 1;
    

    The operands of the + operator have the "usual arithmetic conversions" applied to them, which in this case means that both operands are promoted to int. Since int is more that wide enough to hold the result, there's no overflow; the result is 128, and is of type int. When that result is stored back into variable, it's converted from int to char.

    The rules for overflow are different for conversions than they are for arithmetic operations like "+". For a signed-to-signed or unsigned-to-signed conversion, if the value can't be represented in the target type, the behavior is not undefined; it merely yields an implementation-defined result.

    For a typical implementation that uses a 2's-complement representation for signed integer types, the value stored will probably be -128 -- but other behaviors are possible. (For example, an implementation could use saturating arithmetic.)

    Another (rather obscure) possibility is that char and int could be the same size (which can happen only if char is at least 16 bits). That can have some interesting effects, but I won't go into that (yet).

    0 讨论(0)
  • 2021-01-22 03:36

    An overflow occured and results in undefined behavior.

    Section 5.5:

    Ifduring the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined [...]

    The standard goes on to note that integer overflows are, in most implementations, ignored. But this doesn't represent a guarantee.

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