Int or uint or what

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; 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?


, ....

+3
8

: .

1) , , 3 int.MaxValue, . .NET , , checked , OverflowException.

2) , var, , . , Int32s Int32, UInt32, Int64 - . , , Int32, Int32.

3) .

+6
 1)  -2147483646 is bigger than -2,147,483,648
 2) 2147483648 is out of range
 3) int is an alias for Int32
+3

1)
, -2147483646, -2147483648. .

, int -2147483646. -2147483648..2147483647.

2)
. int, , int, , .

, , , .

3)
.

+3
  • , .
  • , .
  • int System.Int32, .Net.
+1

-

Int32, char (8 )

,

7 128 0111 1111

129-, 1000 0001, , -1

+1

.NET .
(32-) , +3 .

, :

int a = 2147483647;
double b = a / 4;

int a = 2147483647;
var b = a / 4;

.

:
, .NET .
, , .

0

, .

, Mersenne prime 0x7FFFFFFF

0

, ,

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.

0
source

Source: https://habr.com/ru/post/1732703/


All Articles