#166 – Using the for Statement to Create an Infinite Loop

You can create an infinite loop using either while or for.

In the example below, the body of the for loop will run forever.

            // Run forever
            for (;;)
            {
                AskUserATriviaQuestion();
                TellThemTheCorrectAnswer();
            }

You can accomplish the same thing using while (true), but you might still use the for loop if you want to use a loop variable.

            // Run forever
            for (uint questionNumber = 1; ; questionNumber++)
            {
                AskUserATriviaQuestion(questionNumber);
                TellThemTheCorrectAnswer(questionNumber);
            }
Advertisement

#159 – A while Loop Might Execute Forever

If the boolean expression that controls a while loop never evaluates to false, the loop might continue to execute indefinitely.  This is known as an infinite loop.

You might create an infinite loop by design, or it might in fact be a programming error.  The only way to end an infinite loop is to kill the parent process.

In the following example, we just use the value of true for the loop expression, so that the loop will continue to execute indefinitely.

            uint digit = 1;

            while (true)
            {
                CalculateNthDigitOfPi(digit);
                RecordNthDigitOfPi(digit);
                digit++;
            }

In the example below, we intend for Sisyphus to roll his rock up the hill ten times.  We intend to decrement the numRolls variable, but mistakenly increment it.  This leads to an infinite loop, with Sisyphus doomed to roll his rock up the hill forever.

            uint numRolls = 10;

            while (numRolls > 0)
            {
                SisyphusRollRockUphill();
                numRolls++;
            }