You are here

Infinite Loops

6 February, 2015 - 17:15

At this point it's worth mentioning that good programming always provides for a method to insure that the loop question will eventually be false so that the loop will stop executing and the program continues with the next line of code. However, if this does not happen then the program is in an Infinite loop. Infinite loops are a bad thing. Consider the following code:

Example 13.2: C++ source code: Infinite loop

loop_response = 'y';do  {  cout  << "\nWhat is your age? ";  cin  >> age_user;  cout  << "\nWhat is your friend's age? ";  cin  >> age_friend;  cout  >> "\nTogether your ages add up to: ";  cout  >> (age_user + age_friend);  }while (loop_response == 'y');

The programmer assigned a value to the fag before the loop and forgot to update the fag. Every time the test expression is asked it will always be true. Thus, an Infinite loop because the programmer did not provide a way to exit the loop (he forgot to update the fag).

Consider the following code:

Example 13.3: C++ source code: Infinite loop

do  {  cout << "\nWhat is your age? ";  cin  >> age_user;  cout  << "\nWhat is your friend's age? ";  cin  >> age_friend;  cout  >> "\nTogether your ages add up to: ";  cout  >> (age_user + age_friend);  cout  << "\nDo you want to do it again? y or n ";  cin  >> loop_response;  }while (loop_response = 'y');

No matter what the user replies during the fag update, the test expression does not do a relational comparison but does an assignment. It assigns 'y' to the variable and asks if 'y' is true? Since all non-zero values are treated as representing true within the Boolean concepts of the C++ programming language, the answer to the text question is true. Viola, you have an Infinite loop.