while (1) Loops in C++

By: Reema sen Viewed: 153433 times  Printer Friendly Format    


The condition tested in a while loop can be any valid C++ expression. As long as that condition remains true, the while loop will continue. You can create a loop that will never end by using the number 1 for the condition to be tested. Since 1 is always true, the loop will never end, unless a break statement is reached. The following c++ program demonstrates counting to 10 using this construct.

while (1) loops.

1:    // 
2:    // Demonstrates a while true loop
3:
4:    #include <iostream.h>
5:
6:    int main()
7:    {
8:      int counter = 0;
9:
10:      while (1)
11:      {
12:         counter ++;
13:         if (counter > 10)
14:             break;
15:      }
16:      cout << "Counter: " << counter << "\n";
17:       return 0;
18: 
Output: Counter: 11

Analysis: On line 10, a while loop is set up with a condition that can never be false. The loop increments the counter variable on line 12 and then on line 13 tests to see whether counter has gone past 10. If it hasn't, the while loop iterates. If counter is greater than 10, the break on line 14 ends the while loop, and program execution falls through to line 16, where the results are printed.
This program works, but it isn't pretty. This is a good example of using the wrong tool for the job. The same thing can be accomplished by putting the test of counter's value where it belongs--in the while condition.

 


WARNING: Eternal loops such as while (1) can cause your computer to hang if the exit condition is never reached. Use these with caution and test them thoroughly.

C++ gives you many different ways to accomplish the same task. The real trick is picking the right tool for the particular job.

 


DON'T use the goto statement. DO use while loops to iterate while a condition is true. DO exercise caution when using continue and break statements. DO make sure your loop will eventually end.


Most Viewed Articles (in C++ )

Latest Articles (in C++)

Comment on this tutorial