Behavior of increment operator at bounds for character type

前端 未结 2 1238
小鲜肉
小鲜肉 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: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.

提交回复
热议问题