Search code examples
integer-overflowsystems-programming

Why is the product of two positive integers a negative integer?


This semester i took system proramming course. Why 50000*50000 will be negative? I try to understand logic of this. Here is the screenshot of the slide

slide image


Solution

  • This is because in most programming languages, the integer data type has a fixed size.

    That means that each integer value have a defined MIN and MAX value.

    For example in C# MAX INT is 2147483647 and MIN is -2147483648 In PHP 32 bits it's 2147483647 and -2147483648 In PHP 64 bits it's 9223372036854775807 and -9223372036854775808

    What happen when you try to go over that value? Simply the computer will make what's called an integer overflow and the value will loop back to the min value.

    In other words, in C# 2147483647 + 1 = -2147483648 (assuming you use an integer datatype, not long or float). That exactly what happen with 50000 * 50000, it just goes over max value and loop from the next value.

    The exact min and max values are dependent on the language used, the platform the code is built, the platform the code is run on and the static type of the value.

    Hope it clears everything out for you!