Is Signed Integer Overflow Still Undefined Behavior in C ?
As defined in the C 11 standard, signed integer overflow remains undefined behavior. Despite the cstdint documentation stating that int8_t, int16_t, int32_t, and int64_t types use 2's complement for negative values, overflow behavior is still considered undefined.
The C 11 Standard in Paragraph 5/4 emphatically states:
**If during 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.**
Therefore, even though a two's complement representation is employed for these signed types, arithmetic modulo 2^n is not implicitly assumed during evaluation.
Conversely, the C 11 Standard explicitly specifies in Paragraph 3.9.1/4 that unsigned arithmetic adheres to modular arithmetic:
Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2^n where n is the number
of bits in the value representation of that particular size of integer
Consequently, unsigned arithmetic operations are always mathematically definable, and the resulting value is within the representable range, thus exempting it from the undefined behavior clause. Footnote 46 further clarifies this:
This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting
unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the
resulting unsigned integer type.
In summary, while the use of 2's complement representation for signed types provides well-defined behavior for negative values, integer overflow for these types remains undefined behavior in C , as the Standard overrides any implementation-dependent behavior.
The above is the detailed content of Is Signed Integer Overflow Still Undefined Behavior in C ?. For more information, please follow other related articles on the PHP Chinese website!