while (1) Loops in C++

By: Reema sen 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.


Ask a Question



Most Viewed Articles (in C++ )

Latest Articles (in C++)

Comment on this tutorial

Ask a Question

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. i should say, a lot of thank you because of this s
View Tutorial          By: merven at 2009-03-17 09:45:39

2. nested for loop
View Tutorial          By: SAJAN at 2011-03-15 12:42:36

3. #include <iostream>
using namespace s

View Tutorial          By: Jorgeus at 2012-08-30 09:07:03

4. Thanks a LOT !!
I was confused with this !

View Tutorial          By: rishabhsethi at 2012-10-31 15:07:07

5. hi
View Tutorial          By: batbold at 2013-04-09 07:13:06

6. Very informative.
View Tutorial          By: Loops in C++ at 2015-01-23 14:18:58