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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With