In this C++ tutorial, you will learn about infinite For loop, and how to create an infinite For loop, with the help of example programs.
Infinite For Loop in C++
To make a C++ For Loop run indefinitely, the condition in for statement has to be true whenever it is evaluated. To make the condition always true, there are many ways.
Flowchart – Infinite For Loop
Following is the flowchart of infinite for loop in C++.
As the condition is never going to be false, the control never comes out of the loop, and forms an Infinite Loop as shown in the above diagram, with blue paths representing flow of infinite for loop.
Examples
1. Infinite For loop with condition=true
For Loop condition is a boolean expression that evaluates to true or false. So, instead of providing an expression, we can provide the boolean value true
, in place of condition, and the result is an infinite for loop.
C++ Program
#include <iostream>
using namespace std;
int main() {
for (; true; ) {
cout << "hello" << endl;
}
}
Output
hello
hello
hello
hello
Note: You will see the string hello
print to the console infinitely, one line after another. If you are running from command prompt or terminal, to terminate the execution of the program, enter Ctrl+C
from keyboard. If you are running the program from an IDE, click on stop button provided by the IDE.
2. Infinite For loop with condition that always evaluates to true
Instead of giving true
boolean value for the condition in for loop, you can also give a condition that always evaluates to true. For example, the condition 1 == 1
or 0 == 0
is always true. No matter how many times the loop runs, the condition is always true and the for loop will run forever.
C++ Program
#include <iostream>
using namespace std;
int main() {
for (; 1 == 1; ) {
cout << "hello" << endl;
}
}
Output
hello
hello
hello
hello
.
.
3. Infinite For loop with no update to control variables
These type of infinite for loops may result when you forget to update the variables participating in the condition.
In the following example, we have initialized variable i
to 0
and would like to print a string to console while the i
is less than 10
. Typically, in the following example, one would increment i
in the update section of for loop statement, to print hello
10 times. But, if we have not updated i
in neither the for loop body nor for loop update section, i
would never change. This could make the loop an infinite while loop.
C++ Program
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 10; ) {
cout << "hello" << endl;
}
}
Output
hello
hello
hello
hello
Conclusion
In this C++ Tutorial, we learned how to write an Infinite For Loop in C++, with the help of example programs.