Watch window has different value when double cast to int

  • Thread starter Thread starter Israel
  • Start date Start date
I

Israel

(disclaimer: forget the fact that it's not a wise idea to blindly cast
a double to an int)

If you debug the following code:
double ThresholdHigh = 9e+9;
double ThresholdHigh_int = (int)ThresholdHigh;

And then add both of these to the watch window:
ThresholdHigh_int
(int)ThresholdHigh

They will have different values after executing the above code. The
first will be -2147483648 and the second will be 410065408.

I'm using DevStudio 2005.
 
Israel said:
(disclaimer: forget the fact that it's not a wise idea to blindly cast
a double to an int)
Well no, let's not, because it's at the heart of your question. :-)
If you debug the following code:
double ThresholdHigh = 9e+9;
double ThresholdHigh_int = (int)ThresholdHigh;

And then add both of these to the watch window:
ThresholdHigh_int
(int)ThresholdHigh

They will have different values after executing the above code. The
first will be -2147483648 and the second will be 410065408.
That's because 9000000000 doesn't fit in an int. When casting in .NET, this
will be checked and the int will be set to int.MinValue, apparently. If you
turn on overflow checking, you'll get an exception instead.

When viewing this in the debugger, the debugger doesn't actually emit code
to perform this cast in IL. Instead, it computes what is equivalent to (int)
((long) 9e+9). Try it. I'm guessing it uses 64-bit arithmetic internally.

Expressions in the watch window are very close to actual .NET code, but not
*exactly*. This makes sense, as it would be very slow to give them a full
compiler pass.
 
Back
Top