Home  >  Article  >  Backend Development  >  C# difficulties are solved one by one (7): checked and unchecked

C# difficulties are solved one by one (7): checked and unchecked

黄舟
黄舟Original
2016-12-22 14:20:341014browse

C# By default, if the value of a constant expression exceeds the maximum value of the target type, a compilation error will occur.

C# difficulties are solved one by one (7): checked and unchecked


If the target data type cannot accommodate the data of non-constant expressions, the data will be truncated during assignment.

class Program 
{ 
static void Main(string[] args) 
{ 
int n = int.MaxValue;//n=2147483647 
n = n + 1; 
System.Console.WriteLine(n); 
} 
}

C# difficulties are solved one by one (7): checked and unchecked

At this time, it can be explained by memory storage data. Previously, int.MaxValue was 32-bit 1 in the memory. After adding 1, it becomes 32-bit 0. At this time, 0 is considered to be a negative sign, so it will be obtained -2147483648.

Placing the above code in the checked block will cause a System.OverflowException type.

class Program 
{ 
static void Main(string[] args) 
{ 
checked 
{ 
int m = int.MaxValue; 
m = m + 1; 
System.Console.WriteLine(m); 
} 
} 
}

C# difficulties are solved one by one (7): checked and unchecked

For variables placed in checked blocks in C#, if an overflow assignment occurs during runtime, an exception will be thrown.

unchecked is used to cancel overflow checking of integer arithmetic operations and conversions.

The above is the content of C# difficulties one by one (7): checked and unchecked. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn