7

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!

1 Answer 1

26

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

Maybe runtime could be more flexible and automatically "expand" calculation if it sees that expression will be stored in long ?
@Petar: I think that would be a bad idea. It would make the language much more complicated. It's easy to avoid this problem, and it keeps the language simple - there are a few places where the meaning of an expression depends on its context (e.g. lambda expressions) but I don't want to see more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.