The increment is forever and you get -2147483648?

For a smart and complex reason that I really don't want to explain (because it is due to the fact that the timer was extremely ugly and hacked), I wrote several types of C # code something like this:

int i = 0;
while (i >= 0) i++; //Should increment forever
Console.Write(i);

I expected the program to hang or crash forever or something like that, but, to my surprise, after waiting about 20 seconds or so, I get this output:

-2147483648

Well, programming taught me a lot of things, but I still can’t understand why a constant increase in the number leads to the fact that it will ultimately be negative ... what is happening here?

+3
source share
9 answers

# . int 32 . 32 4 294 967 296 ( 2 ^ 32), , .

int , , - . . 1, .

int, :

 Hexadecimal        Decimal
 -----------    -----------
 0x80000000     -2147483648
 0x80000001     -2147483647
 0x80000002     -2147483646
    ...              ...
 0xFFFFFFFE              -2
 0xFFFFFFFF              -1
 0x00000000               0
 0x00000001               1
 0x00000002               2
     ...             ...
 0x7FFFFFFE      2147483646
 0x7FFFFFFF      2147483647

, , , - , , , . , "integer overflow". , , checked unchecked #. , , .

representation 2 .

+9

32- , 0xFFFFFFFF, -2147483648 . , 31- .

, unsigned int, , 32- .

+7

, , .

, , , . , 1 , , . , ( ).

+2

int - . max ( ) 0.

uint , .

+2

:

int i = 0;
while (i >= 0) 
   checked{ i++; } //Should increment forever
Console.Write(i);

+2

. -, ( , - ), BigInteger System.Numerics(.NET 4+). .

+1

, , "i" int, .

0

, ( ).

, : 12:25 . , , , .

0

, , , snarky.

, , - , .

, 1- , , (, , , , .. ).

My advice is to get reading material on the 1st annual computer science + Knut Book "The Art of Computer Pragming", and for ~ $ 500 you will have everything you need to become an excellent programmer, much cheaper than a whole Uni course; -)

-1
source

All Articles