Iterating until int.MaxValue reached

匆匆过客 提交于 2019-12-01 10:51:52

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 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;
    } 
}

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'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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!