Home >Backend Development >C++ >Why Does Integer Overflow Produce Unexpected Results in C ?

Why Does Integer Overflow Produce Unexpected Results in C ?

DDD
DDDOriginal
2024-11-12 16:47:01240browse

Why Does Integer Overflow Produce Unexpected Results in C  ?

Unexpected Results with Integer Overflow in C

When working with integer types, it's essential to understand the implications of overflow. In this post, we explore why signed and unsigned integer overflows yield unexpected results in a C program.

Consider the following program that tests integer overflow:

#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;
}

The output is surprising:

0
2147483647
-2147483648

0
4294967295
0

Signed Integer Overflow

Signed integer overflow is undefined behavior. This means that the compiler can do anything it wants, including producing an incorrect result like in this case.

Unsigned Integer Overflow

In contrast, unsigned integer overflow is well-defined. The value wraps around, akin to a modulo division by 2^bits (where bits is the number of bits in the data type). Since we have a 32-bit int:

4294967295 + 1 = 4294967296 % 2^32 = 0

Specific Implementation Details

Even though signed integer overflow is undefined behavior, most implementations use 2's complement representation. This explains the specific results observed in this program:

  • POS_MAX (maximum positive value) = 7 (0111)
  • NEG_MAX (maximum negative value) = -8 (1000)

When adding 1 to POS_MAX:

0111 + 1 = 1000

Since the leading bit is set, it's a negative number. To find the actual value, we perform 2's complement inverse:

1000 - 1 = 0111
~0111 = 1000 = -8

Thus, the final value is -8, which appears in the program's output.

The above is the detailed content of Why Does Integer Overflow Produce Unexpected Results in C ?. 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