As a little test I wanted to see how long it would take to count to int.MaxValue in a C# console application. Every few hours I checked the progress. Last night when I thoug
Your for loop:
for (int counter=0; counter <=numToCountTo ; counter++)
is incorrect. It will execute while counter <= int.MaxValue which is ALWAYS true. When it increments it it will roll to int.MinValue and keep incrementing.
Change it to
for (int counter=0; counter < numToCountTo ; counter++)
or use a long for your loop counter:
for (long counter=0; counter <= numToCountTo ; counter++)
You can also use a do...while loop since the loop is executed before the breaking condition is evaluated:
int counter = 0;
do
{
...
counter++;
}
while(counter < numToCountTo);
It's called an overflow - the integer wraps around to the lowest possible negative value.
If you want it to stop at maxInt you should replace the <= with a < - at present you can never stop the loop as counter can never be bigger can maxIni.
When you add 1 to an Int32.MaxValue you will end up with Int32.MinValue.
int a = Int32.MaxValue;
a++; // a is now -2147483648
It will continue because counter will never be > than int.MaxValue, if you do int.MaxValue+1 it will wrap down to int.MinValue.
Thus, your for condition is always true.
An alternative I would recommend is either use a larger datatype for your counter like long, or change your loop to:
int counter = -1;
for(;;) // while(true)
{
counter++;
Console.WriteLine("{0}", counter);
if (counter == int.MaxValue)
{
break;
}
}