Search code examples
c++integerinteger-overflow

Why is my output negative? I am multiplying 2 positive numbers?


The expected output of the following program is the first perfect square number, whose last two digits are both odd (WHICH DOES NOT EXIST). So instead of returning a blank screen (since such number doesn't exist), the output is -2147479015, which is NEGATIVE.

But the code is cout << i*i, which is obviously non-negative. I looked it up online and saw something about "overflow" but i am not quite understanding what overflow is. When I google it, all I get is overflow attacks , which is not what I want to know.

int main() {
    for(int i =1; ; i++) {
        if(i*i%2 !=0 && i*i/10%2 !=0) {
            cout << i*i;
            return 0;
        }
    }
}

What is overflow? Why is it causing me to get a negative number?


Solution

  • Numeric variables (like your "i", which is an "int") can only hold a limited range of numbers. For the purposes of demonstrating, let's say that there are only four different numbers that an int can hold (obviously, a real int could hold a lot more than that). Those numbers might be -2, -1, 0, and 1.

    If I have an int whose value is 0, and I add 1 to it, I get an int whose value is 1. But if I then add another 1, I do not get an int whose value is 2. Remember, an int cannot possibly have the value 2. It can only have the values -2, -1, 0, or 1.

    So instead, 1 + 1 will "wrap around": When you go "past" the maximum possible value, it wraps back to the minimum possible value. So 1 + 1 = -2.

    That's "overflow". What's happening to you is the same thing, but with multiplication rather than addition, and of course "int" having many, many more possible values than just four.