Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this produce an overflow exception?

I was testing something out using LinqPad and was surprised that the following code did not produce an exception:

ulong lSmallValue = 5;
ulong lBigValue = 10;

ulong lDifference = lSmallValue - lBigValue;

Console.WriteLine(lDifference);
Console.WriteLine((long)lDifference);

This produces the following output:

18446744073709551611
-5

Fortunately, I was hoping for this behavior, but I was under the assumption that this would cause an OverflowException to be thrown.

From System.OverflowException:

An OverflowException is thrown at run time under the following conditions:

  • An arithmetic operation produces a result that is outside the range of the data type returned by the operation.
  • A casting or conversion operation attempts to perform a narrowing conversion, and the value of the source data type is outside the range of the target data type.

Why doesn't the operation lSmallValue - lBigValue fall into the first category?

like image 519
Anthony Avatar asked Sep 24 '12 19:09

Anthony


People also ask

Why does Python not overflow?

Arbitrary precision In python 2, there are actually two integers types: int and long , where int is the C-style fixed-precision integer and long is the arbitrary-precision integer. Operations are automatically promoted to long if int is not sufficient, so there's no risk of overflowing.

What causes an overflow error?

In general, a data type overflow error is when the data type used to store data was not large enough to hold the data. Furthermore, some data types can only store numbers up to a certain size. An overflow error will be produced, for example, if a data type is a single byte and the data to be stored is greater than 256.

How do I fix stack overflow exception?

Setting the size of the stack or the maximum depth value of the recursion is allowed in most of the programming languages. Now that we have an opportunity to set the value of the depth of the stack, we have to set to a value as small as possible and observe the output.

What is overflow exception in C++?

Overflow Error. Occurs when the result is either infinite, or too large to represent in the numeric type being returned by the function. Underflow Error. Occurs when the result is not zero, but is too small to be represented by any other value in the type being returned by the function.


1 Answers

CLR will not throw the Overflow exception by default. Unless you're using the "checked" keyword.

http://msdn.microsoft.com/en-us/library/74b4xzyw%28v=vs.71%29.aspx

UPD: Actually, I do recommend the "CLR via C#" by Jeffrey Richter - he makes these things so much more transparent. My favorite book about the CLR and C# fundamentals.

like image 139
Mikhail Avatar answered Oct 06 '22 09:10

Mikhail