One of the int counters I was using was close to minus 2 billion. I'm only adding positive numbers, how can that happen???
OK, this one is enough. Sorry for your 30 years of experience: perhaps you learned some FORTRAN (I used it, too, in the very beginning, before I realized it does not worth the effort), but you did not get to understanding some of very basic fundamentals of computing. Of course, adding to the integer number
must end up having a negative number.
What you are talking about have nothing to do with stack overflow. If you want to know how stack and stack overflow works, it should be a separate question. This is integer overflow.
Of course you did not find a bug in C#, but you did find one in your understanding. Not a big deal: just fix it. You will find complete and comprehensive explanation here:
http://en.wikipedia.org/wiki/Two%27s_complement.
The thing is: you are using a system where signed integers are interpreted using
two's complement representation. This representation is very practical: it allows for CPU to perform arithmetic operations using no information about a type of integer number, signed or unsigned or operands of different types. Also, it exclude the presence of -0 and +0 as different objects.
For more background on the topic, please see:
http://en.wikipedia.org/wiki/Signed_number_representations as well as Web links found in this article.
[EDIT]
To get calculation sensitive to integer overflow do them under
checked
mode:
checked {
int myInt = 1 << 30;
myInt = myInt * 2;
}
Maximum 32-bit
int
is
(int)0x7fffffff
, isn't that obvious?
[END EDIT]
Good luck,
—SA