Question

Can someone explain me the reason of overflow in variable a? Note that b is bigger than a.

static void Main(string[] args)
{
     int i = 2;    
     long a = 1024 * 1024 * 1024 * i;
     long b = 12345678901234567;
     System.Console.WriteLine("{0}", a);
     System.Console.WriteLine("{0}", b);
     System.Console.WriteLine("{0}", long.MaxValue);
}

-2147483648
 12345678901234567
 9223372036854775807
 Press any key to continue . . .

Thanks!

Was it helpful?

Solution

The RHS is an int multiplication because every part of the expression is an int. Just because it's being assigned to a long doesn't mean it's performed with long arithmetic.

Change it to:

long a = 1024L * 1024 * 1024 * i;

and it'll work. (The difference is the L at the end of the first 1024.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top