views:

177

answers:

5

Is there a way to configure the VS2008 C# compiler to give a warning for code like this:

Int64 x = 123456789000;
Int32 y = (Int32)x;
A: 

go to the properties view of a project, click the Build tab, click the Advanced button at the bottom right, check the "Check for arithmetic overflow/underflow" checkbox

Derick Bailey
This will cause overflow checking code to be inserted which results in a runtime exception, not a compile-time warning.
Joey
+2  A: 

The compiler cant do that at compile time, but you can configure it to throw exeptions at run-time,

In the project-properties->Build->Advanced->Check overflow\underflow

MindFold
+10  A: 

The whole point of an explicit cast is to say that "I take responsibility for the problem, please just do it."

In your trivial case, it would perhaps be easy for the compiler to figure out that the value would not fit in a Int32, and thus produce your warning.

However, what about this:

Int64 x = CallSomeMethod();
Int32 y = (Int32)x;

How can it warn you about this? Should it:

  1. try to figure out what kind of range the value from CallSomeMethod could return?
  2. always warn? (then what would the point be?)

The best you can hope for here is to have a runtime check, or similar, the compiler cannot prevent you from everything that could go wrong.

Lasse V. Karlsen
+4  A: 

All necessary casts might cause data loss. The purpose of a cast is to tell the compiler "I'm doing something dangerous here that you cannot analyze, but I know what I'm doing". Since the entire purpose of a cast is to handle a case that the compiler is not smart enough to analyze, expecting the compiler to analyze it in order to give a warning seems pointless.

Therefore, your proposal is effectively to make a warning for every necessary cast, which seems counterproductive.

I note that an implicit conversion can also cause data loss in some rare cases. Implicit conversions may lose bits of precision; what an implicit conversion preserves is magnitude.

Eric Lippert
+1  A: 

I agree with Lasse V. Karlsen's explicit cast explanation.

One possible solution for you in this case is to actually remove the explicit casts (find and replace them ) in your code if you're truly looking to have "warnings" when a cast like that exists.It would mean you would have to manually go through all the casts that occurred (in the warning list) and determine if they're valid or not. so your code would look like this:

Int64 x = 123456789000;
Int32 y = x;
CrimsonX