Home > Backend Development > C++ > body text

Why does integer overflow in C lead to different results for signed and unsigned integers?

Patricia Arquette
Release: 2024-11-12 01:37:03
Original
737 people have browsed it

Why does integer overflow in C   lead to different results for signed and unsigned integers?

Unexpected Results from Signed/Unsigned Integer Overflow

In C , integer overflow can lead to unexpected results depending on the signedness of the data type.

Consider the following program:

#include <iostream>

int main()
{
    int x(0);
    std::cout << x << std::endl;

    x = x + 2147483647;
    std::cout << x << std::endl;

    x = x + 1;
    std::cout << x << std::endl;
    std::cout << std::endl;

    unsigned int y(0);
    std::cout << y << std::endl;

    y = y + 4294967295;
    std::cout << y << std::endl;

    y = y + 1;
    std::cout << y << std::endl;
}
Copy after login

The output of this program may surprise you:

0
2147483647
-2147483648

0
4294967295
0
Copy after login

Explanation

For signed integers, overflow behavior is undefined. In most implementations, 2's complement is used, which leads to unexpected wrapping-around behavior. For instance, in the program above:

  • x is initialized to 0 and then overflows to its maximum positive value, 2147483647.
  • When 1 is added to this overflowed value, it wraps around to its minimum negative value, -2147483648.

For unsigned integers, overflow is well-defined and wraps around modulo 2bits. In other words, the value is reset to 0 when overflowing the maximum. This explains the output for y, where y wraps around to 0 after overflowing the maximum unsigned value, 4294967295.

It's important to note that the behavior for signed integer overflow is not guaranteed by the language and may vary depending on the implementation and machine architecture. Therefore, it's generally not recommended to rely on such behavior in your programs.

The above is the detailed content of Why does integer overflow in C lead to different results for signed and unsigned integers?. 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