Is signed integer overflow still undefined behavior in C++?

前端 未结 3 1440
闹比i
闹比i 2020-11-22 10:56

As we know, signed integer overflow is undefined behavior. But there is something interesting in C++11 cstdint documentation:

signed inte

3条回答
  •  渐次进展
    2020-11-22 11:19

    Just because a type is defined to use 2s complement representation, it doesn't follow that arithmetic overflow in that type becomes defined.

    The undefined behaviour of signed arithmetic overflow is used to enable optimisations; for example, the compiler can assume that if a > b then a + 1 > b also; this doesn't hold in unsigned arithmetic where the second check would need to be carried out because of the possibility that a + 1 might wrap around to 0. Also, some platforms can generate a trap signal on arithmetic overflow (see e.g. http://www.gnu.org/software/libc/manual/html_node/Program-Error-Signals.html); the standard continues to allow this to occur.

提交回复
热议问题