Consider this
int i = 2147483647; var n = i + 3; i = n; Console.WriteLine(i); // prints -2147483646 (1) Console.WriteLine(n); // prints -2147483646 (2) Console.WriteLine(n.GetType()); // prints System.Int32 (3)
The following confuse me
(1) how can int save the value -2147483646? (int range = -2,147,483,648 to 2,147,483,647).(2) why this print is -2147483648, but not 2147483648 (the compiler should choose the best type as int range exceeds)(3) if it converts somewhere, why does n.GetType () give System.Int32?
Edit1: Bug fix: now you get what I get. (Sorry for this)
var n = i + 1; tovar n = i + 3;
var n = i + 1; to
var n = i + 3;
Edit2: One more thing, if it's overflow, why is the exception not thrown?
Addition: since overflow occurs, is it wrong to set the type for
var n
in the instructions var n = i + 3;for another type?
, ....
: .
1) , , 3 int.MaxValue, . .NET , , checked , OverflowException.
checked
OverflowException
2) , var, , . , Int32s Int32, UInt32, Int64 - . , , Int32, Int32.
var
3) .
1) -2147483646 is bigger than -2,147,483,648 2) 2147483648 is out of range 3) int is an alias for Int32
1), -2147483646, -2147483648. .
, int -2147483646. -2147483648..2147483647.
2). int, , int, , .
, , , .
3).
int
System.Int32
-
Int32, char (8 )
,
7 128 0111 1111
0111 1111
129-, 1000 0001, , -1
1000 0001
.NET .(32-) , +3 .
, :
int a = 2147483647; double b = a / 4;
int a = 2147483647; var b = a / 4;
.
:, .NET ., , .
, .
, Mersenne prime 0x7FFFFFFF
, ,
abc = checked(i+3)
instead of this. This will check the overflow.
Also, in C #, the default value should not throw an exception when overflowing. But you can switch this option somewhere on your project properties.
Source: https://habr.com/ru/post/1732703/More articles:The button style has a tight border for page loading when several buttons are on the page - javascriptИспользовать $_POST [ "x" ] напрямую или скопировать локальную переменную, а затем использовать? - standardsОбъекты ядра iPhone Core добавлены в NSMutableArray - nsmutablearrayASP.Net when post back get Specified URL not found - asp.netas for the private javascript method - javascriptDetecting Drag'n'Drop and Paste with contentEditable or designMode enabled - javascriptlinq for object - include with lambda expression - lambdastatic construction of variables in C ++ - c ++Where can I get fancy red and green UIButtons like "End Call" etc.? - designCreating chart / statistics for selected mysql table via python - pythonAll Articles