As we know, signed integer overflow is undefined behavior. But there is something interesting in C++11 cstdint
documentation:
signed inte
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.