Rahul Soni's blog

Never assume the obvious is true!

MSIL Trivia - 4 (Spot the difference)

MSIL Trivia - 4 (Spot the difference)

  • Comments 4

I have created a very simple C# console application which gives me the following MSIL code when compiled... The next screenshot has almost the same code but with some special difference. Can you tell me what could have caused it and is it good or bad?

image

 

image

I will answer this in the comments (or next post as necessary) Happy.

Until then... Wave 

Cheers,
Rahul


Quote of the day:
I'm a great believer in luck, and I find the harder I work the more I have of it. - Thomas Jefferson
  • PingBack from http://msdnrss.thecoderblogs.com/2008/03/12/msil-trivia-4-spot-the-difference-2/

  • You local variable (V_0) is of type Int16. One of those 16 bits is used for the sign, leaving 15 for a maximum value of 2^15 or 0x7FFF.

    You then create a Int32 value, set to 0x7FFF, and then assign it to the above local. Next you output the value.

    Up to this point, everything is OK.

    Next, you increment V_0 by one. As already noted, signed 16-bit values have a maximum value of 32767, so it naturally overflows to -32768.

    In your next version, you use checked addition and checked conversion (back to an Int16). This check detects the overflow and throws the appropriate exception.

    Good or bad, it really depends on what you are trying to do. Some algorithms rely on rollovers. Human arithmetic typically do not expect such behavior.

  • Perhaps, either you used C#(unless you used the Checked option, which is not the default in C#, by default it is unchecked) in the first and VB.Net in the second.

    There is a check for overflow (add.ovf) only in VB.Net (as opposed to add in C# by default). Conv.ovf.i2 Converts an int16 on the stack to int32 and throws an exception on overflow.

    So if your data overflowed in the second case you will get an exception, and in the 1st case you may see an unexpected result. This is what i feel.

  • Great explanation Anon and Saurabh, you were pretty close too. That gives me very little scope to add to this comment :-)

    But just to close the loop, I wanted to add that I didn't really modify the code in any way (I mean, I did't add checked{} manually into the code). Although, adding checked would do the same exact thing.

    In fact, Anon was bang on target about what I had done. The only change which I did was while compiling I used the switch /checked and it generated the code appropriately for me.

    Cheers,

    Rahul

Page 1 of 1 (4 items)
Leave a Comment
  • Please add 2 and 3 and type the answer here:
  • Post