C # By default, if the value of a constant expression exceeds the maximum value of the target type, a compilation error will result.
If the target data type cannot hold data for a very few expressions, the data is truncated when it is assigned.
Copy Code code as follows:
Class Program
{
static void Main (string[] args)
{
int n = Int. maxvalue;//n=2147483647
n = n + 1;
System.Console.WriteLine (n);
}
}
At this time the memory is available to store data to interpret before int. MaxValue in memory for 32-bit 1, since the addition of 1 to 32-bit 0, when 0 is considered to be a minus sign, so it will come to-2147483648.
Placing the above code in a checked block will raise the System.OverflowException type.
Copy Code code as follows:
Class Program
{
static void Main (string[] args)
{
Checked
{
int m = Int. MaxValue;
m = m + 1;
System.Console.WriteLine (m);
}
}
}
A variable in C # that is placed inside a checked block throws an exception if an overflow assignment occurs at run time.
unchecked is used to cancel overflow checking of integer arithmetic operations and conversions.