开发者

Increment forever and you get -2147483648?

开发者 https://www.devze.com 2023-03-10 01:07 出处:网络
For a clever and complicated reason that I don\'t really want to explain (because it involves making a timer in an extremely ugly and hacky way), I wrote some C# code sort of like this:

For a clever and complicated reason that I don't really want to explain (because it involves making a timer in an extremely ugly and hacky way), I wrote some C# code sort of like this:

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

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

-2147483648

Well, programming has taught me many things, but I still cannot grasp why continually incrementing a number causes it to 开发者_如何学编程eventually be negative...what's going on here?


In C#, the built-in integers are represented by a sequence of bit values of a predefined length. For the basic int datatype that length is 32 bits. Since 32 bits can only represent 4,294,967,296 different possible values (since that is 2^32), clearly your code will not loop forever with continually increasing values.

Since int can hold both positive and negative numbers, the sign of the number must be encoded somehow. This is done with first bit. If the first bit is 1, then the number is negative.

Here are the int values laid out on a number-line in hexadecimal and decimal:

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

As you can see from this chart, the bits that represent the smallest possible value are what you would get by adding one to the largest possible value, while ignoring the interpretation of the sign bit. When a signed number is added in this way, it is called "integer overflow". Whether or not an integer overflow is allowed or treated as an error is configurable with the checked and unchecked statements in C#. The default is unchecked, which is why no error occured, but you got that crazy small number in your program.

This representation is called 2's Complement.


The value is overflowing the positive range of 32 bit integer storage going to 0xFFFFFFFF which is -2147483648 in decimal. This means you overflow at 31 bit integers.

It's been pointed out else where that if you use an unsigned int you'll get different behaviour as the 32nd bit isn't being used to store the sign of of the number.


What you are experiencing is Integer Overflow.

In computer programming, an integer overflow occurs when an arithmetic operation attempts to create a numeric value that is larger than can be represented within the available storage space. For instance, adding 1 to the largest value that can be represented constitutes an integer overflow. The most common result in these cases is for the least significant representable bits of the result to be stored (the result is said to wrap).


int is a signed integer. Once past the max value, it starts from the min value (large negative) and marches towards 0.

Try again with uint and see what is different.


Try it like this:

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

And explain the results


What the others have been saying. If you want something that can go on forever (and I wont remark on why you would need something of this sort), use the BigInteger class in the System.Numerics namespace (.NET 4+). You can do the comparison to an arbitrarily large number.


It has a lot to do with how positive numbers and negative numbers are really stored in memory (at bit level).

If you're interested, check this video: Programming Paradigms at 12:25 and onwards. Pretty interesting and you will understand why your code behaves the way it does.


This happens because when the variable "i" reaches the maximum int limit, the next value will be a negative one.


I hope this does not sound like smart-ass advice, because its well meant, and not meant to be snarky.

What you are asking is for us to describe that which is pretty fundamental behaviour for integer datatypes.

There is a reason why datatypes are covered in the 1st year of any computer science course, its really very fundamental to understanding how and where things can go wrong (you can probably already see how the behaviour above if unexpected causes unexpected behaviour i.e. a bug in your application).

My advice is get hold of the reading material for 1st year computer science + Knuth's seminal work "The art of computer pragramming" and for ~ $500 you will have everything you need to become a great programmer, much cheaper than a whole Uni course ;-)

0

精彩评论

暂无评论...
验证码 换一张
取 消