Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in overflow behavior for same program in C# and VB.Net

Tags:

c#

vb.net

I ran a program in .Net 3.5 using C# which works fine

try
{
    int i = 2147483647;

    Console.WriteLine((i * 100 / i).ToString());

    Console.ReadLine();
}
catch (Exception)
{                
    throw;
}

When I run this program in C#, I don't get an exception (it outputs "0"). But when I run this program in VB.Net it results in "Arithmetic operation resulted in an overflow" exception

Try
    Dim i As Integer = 2147483647

    Console.WriteLine((i * 100 / i).ToString())

    Console.ReadLine()
Catch ex As Exception
    Throw
End Try

Why the different behavior between these two languages?

like image 699
Nikhil Agrawal Avatar asked Mar 05 '26 12:03

Nikhil Agrawal


1 Answers

Perhaps looking at the IL will clarify... Simplifying your code a bit:

C#:

int i = 2147483647;
int v = (i * 100 / i);

generates the following IL:

IL_0001:  ldc.i4      FF FF FF 7F 
IL_0006:  stloc.0     // i
IL_0007:  ldloc.0     // i
IL_0008:  ldc.i4.s    64 
IL_000A:  mul         
IL_000B:  ldloc.0     // i
IL_000C:  div         
IL_000D:  stloc.1     // v

while the VB version:

Dim i As Integer = 2147483647
Dim v As Integer
v = i * 100 / i

generates this IL, slightly different:

IL_0001:  ldc.i4      FF FF FF 7F 
IL_0006:  stloc.0     // i
IL_0007:  ldloc.0     // i
IL_0008:  ldc.i4.s    64 
IL_000A:  mul.ovf     
IL_000B:  conv.r8     
IL_000C:  ldloc.0     // i
IL_000D:  conv.r8     
IL_000E:  div         
IL_000F:  call        System.Math.Round
IL_0014:  conv.ovf.i4 
IL_0015:  stloc.1     // v

As you can see, VB is calling mul.ovf, which is "multiply, and check for overflow", and C# is calling mul which does not check for overflow.

Perhaps it doesn't answer your question as to why C# does it one way and VB the other, but at least it answers why it is happening. :)

Edit: see the answer by aquinas to get the "why".

like image 136
Michael Bray Avatar answered Mar 08 '26 02:03

Michael Bray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!