Home > Backend Development > C++ > Does 2's Complement Representation Eliminate Undefined Behavior in C Signed Integer Overflow?

Does 2's Complement Representation Eliminate Undefined Behavior in C Signed Integer Overflow?

Mary-Kate Olsen
Release: 2024-12-23 19:54:09
Original
1001 people have browsed it

Does 2's Complement Representation Eliminate Undefined Behavior in C   Signed Integer Overflow?

Undefined Behavior of Signed Integer Overflow in C

Signed integer overflow, the occurrence when a signed integer's value exceeds its representable range, is well-known to be undefined behavior in C . However, the C 11 cstdint documentation introduces an intriguing statement: negative values in types int8_t, int16_t, int32_t, and int64_t are explicitly specified as being represented using 2's complement.

This specification raises the question: does the use of 2's complement for negative values in these types alter the undefined behavior status of overflow?

The answer, unfortunately, remains yes. According to section 18.4.1 of the C 11 Standard, the header defines all functions, types, and macros identically to section 7.20 of the C standard. Section 7.20.1.1 of the C11 Standard further clarifies the definition of intN_t as signed integer types with 2's complement representation.

Despite this specification of 2's complement representation, the C 11 Standard states unequivocally in section 5/4 that any expression that results in an undefined mathematical result or falls outside the representable range of its type will result in undefined behavior.

Thus, the use of 2's complement for negative values does not imply that arithmetic for these types adheres to modulo 2^n behavior. For unsigned integers, however, the Standard explicitly specifies that the laws of arithmetic modulo 2^n apply, rendering overflow behavior mathematically defined and within the representable range. Consequently, unsigned overflow is not considered undefined behavior.

The above is the detailed content of Does 2's Complement Representation Eliminate Undefined Behavior in C Signed Integer Overflow?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template