views:

78

answers:

4

This compiles

var fourGb = (long)4*1024*1024*1024;

But this fails

var fourGb = 4*1024*1024*1024;

With "The operation overflows at compile time in checked mode".

So if the compiler knows this will be an overflow why cant it infer that the variable type should be a long?

+1  A: 

Imagine the uproar that would cause. "But the compiler can figure out an expression should be evaluated as long, why can't the runtime do it?"

And that's not going to happen, way too expensive.

It is essential that the compiler evaluates expressions the same way as the runtime. If that wasn't the case, editing a constant expression and replacing a constant with a variable could suddenly cause runtime failure. Hard to diagnose failure at that, non-constant expressions are unchecked by default.

Hans Passant
+2  A: 

See http://msdn.microsoft.com/en-us/library/ctetwysk%28VS.80%29.aspx

You asked it to multiple a bunch of ints so the answer is an int according to the C# syntax. Use 'L' if you want a long.

var fourGb = 4L * 1024 * 1024 * 1024;
Hightechrider
A: 

It's the same in most languages:

  • the datatypes of the expression follow precedence rules
  • it's cast to "var" datatype on assignment

Any other behaviour would give unintended consequences

Arguably you've :

gbn
+1  A: 

I don't think it's a good idea to infer the type of variable by the calculation result.

tia