As we know, signed integer overflow is undefined behavior. But there is something interesting in C++11 cstdint
documentation:
signed integer type with width of exactly 8, 16, 32 and 64 bits respectively with no padding bits and using 2's complement for negative values (provided only if the implementation directly supports the type)
And here is my question: since the standard says explicitly that for int8_t
, int16_t
, int32_t
and int64_t
negative numbers are 2's complement, is still overflow of these types an undefined behavior?
Edit I checked C++11 and C11 Standards and here is what I found:
C++11, §18.4.1:
The header defines all functions, types, and macros the same as 7.20 in the C standard.
C11, §7.20.1.1:
The typedef name
intN_t
designates a signed integer type with width N, no padding bits, and a two’s complement representation. Thus,int8_t
denotes such a signed integer type with a width of exactly 8 bits.
Best Answer
Yes. Per Paragraph 5/4 of the C++11 Standard (regarding any expression in general):
The fact that a two's complement representation is used for those signed types does not mean that arithmetic modulo 2^n is used when evaluating expressions of those types.
Concerning unsigned arithmetic, on the other hand, the Standard explicitly specifies that (Paragraph 3.9.1/4):
This means that the result of an unsigned arithmetic operation is always "mathematically defined", and the result is always within the representable range; therefore, 5/4 does not apply. Footnote 46 explains this: