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 thought the program would be done executing, it was executing back to 0. I'm not sure why that happened and I was wondering if anyone could explain it to me. What it did was that it counted to 2,147,483,647 then when this value was reached it began counting backwards to zero. Even though it appeared to be counting backwards, the value had a negative number. I wonder if I needed to use the absolute value of int.MaxValue. Anyway, I was just curious if anyone could see what I'm not seeing. Here is my code. Thanks
static void Main(string[] args)
{
int maxInt = int.MaxValue;
int numToCountTo = maxInt;
//int numToCountTo = 1000000;
try
{
Console.WriteLine(DateTime.Now);
Console.WriteLine("Press any key to begin.");
Console.ReadLine();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int counter=0; counter <=numToCountTo ; counter++)
{
Console.WriteLine(counter);
}
sw.Stop();
TimeSpan ts = sw.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00 Hours}, {1:00 Minutes}, {2:00 Seconds}, {3:00 Milliseconds}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
// ("#,#") places a comma between every 3 digits
Console.WriteLine("It took " + elapsedTime + " to count to " + numToCountTo.ToString("#,#"));
Console.WriteLine("Press Enter key to continue.");
Console.ReadLine();
}
catch (Exception ex)
{
throw new Exception("Exception Reached: " + ex.Message)
}
}
When you add 1 to an
Int32.MaxValue
you will end up withInt32.MinValue
.It will continue because
counter
will never be > thanint.MaxValue
, if you doint.MaxValue+1
it will wrap down toint.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:Your for loop:
is incorrect. It will execute while
counter <= int.MaxValue
which is ALWAYS true. When it increments it it will roll toint.MinValue
and keep incrementing.Change it to
or use a
long
for your loop counter:You can also use a
do...while
loop since the loop is executed before the breaking condition is evaluated: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 ascounter
can never be bigger canmaxIni
.