Search code examples
c#arithmetic-overflow

c#: adding two big integers gives wrong result


So I have a code that adds two integers and prints the result:

Console.WriteLine("enter number: ");
int intTemp = Convert.ToInt32(Console.ReadLine());
long sum = intTemp + 5;
Console.WriteLine($"sum is : {sum}");

But if in the console I will put the maximum value for the int type, I won't get an exception, but the result is wrong, even if I am saving the result in a long variable. Here is the output:

enter number:
2147483647
sum is : -2147483644

But if the sum variable is a long, why I am getting the wrong result?


Solution

  • The result is not of type long. It is of type int and afterwards it is converted to a long in order to assign it to a variable of type long.

    That is needed to do, it is the following:

    long sum = (long)intTemp + 5;
    

    or

    long sum = intTemp + (long)5;
    

    Doing either of the above, since the one operand is of type (long), after conversion, the other would be converted also to long, in order the two values to can be added and the result would be stored to the sum variable.