Simon
Simon

Reputation: 34840

Why cant the compiler infer that a large number is a long?

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?

Upvotes: 3

Views: 165

Answers (4)

Ian Mercer
Ian Mercer

Reputation: 39277

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

You asked it to multiply 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;

Upvotes: 5

tia
tia

Reputation: 9698

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

Upvotes: 2

Hans Passant
Hans Passant

Reputation: 941635

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.

Upvotes: 2

gbn
gbn

Reputation: 432311

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 :

Upvotes: 0

Related Questions