MSIL Trivia – 4 (Spot the difference)

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?




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

Until then... Wave 


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

Comments (4)

  1. Anon. says:

    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.

  2. Saur212 says:

    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.

  3. imRahulSoni says:

    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.



Skip to main content