Reputation: 409
If we are using the following loop in a program, the loop never ends in C# 4.0
for (int i = 1; i <= int.MaxValue; i++)
{
}
This is because adding 1 to int.MaxValue (2147483647) will not result in an overflow exception, but results in -2147483648 (taking into consideration 32bit int and 2's compliment).
int i = int.MaxValue;
Console.WriteLine(i + 1);
It seems the behavior changed recently. See the question Arithmetic operation caused OverflowException .What could be the reason behind this change?
Upvotes: 5
Views: 3025
Reputation: 498992
Overflow exceptions for integer (and other integral types) are only done in checked
contexts.
So, this will cause an exception:
checked
{
int i = int.MaxValue;
Console.WriteLine(i + 1);
}
They are not set to do this by default as they are more expensive than simply overflowing.
From MSDN:
The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.
And:
Overflow checking can be enabled by compiler options, environment configuration, or use of the checked keyword.
This is not a recent change - C# has been like this from day one. What you see in the question is VB.NET code, which is by default in a checked context.
So, keeping to defaults, overflowing code in VB.NET will throw an exception, but identical code in C# will not.
Upvotes: 10