Home >Backend Development >C++ >Is Signed Integer Overflow in C Still Undefined Behavior?

Is Signed Integer Overflow in C Still Undefined Behavior?

Linda Hamilton
Linda HamiltonOriginal
2024-12-25 01:18:25684browse

Is Signed Integer Overflow in C   Still Undefined Behavior?

Signed Integer Overflow in C : Still Undefined Behavior

As highlighted in the C 11 cstdint documentation, signed integer types such as int8_t, int16_t, int32_t, and int64_t utilize 2's complement for negative values. This has sparked the question: does this imply that overflow in these types is no longer considered undefined behavior?

No, overflow of these types remains undefined behavior in C .

According to Paragraph 5/4 of the C 11 Standard, any expression where the result is not mathematically defined or falls outside the representable range of the type results in undefined behavior.

While int8_t, int16_t, int32_t, and int64_t use 2's complement, this does not imply that arithmetic modulo 2^n is applied. The Standard explicitly states 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."

Hence, unsigned arithmetic follows the laws of arithmetic modulo 2^n, and overflow is not undefined behavior. However, for signed arithmetic, overflow remains undefined behavior, regardless of the underlying representation.

The above is the detailed content of Is Signed Integer Overflow in C Still Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn