What is a while(true) Loop in C++?
The while(true) loop, a type of control structure in C++, produces an endless loop. To the extent as what is declared true is always true, the loop will keep running indefinitely.
Syntax
In C++, a while(true) loop’s basic syntax is as follows:
//body executes at infinite times
}
The loop will never end unless a break clause is used inside the loop body because the condition that is true in the previously mentioned syntax will remain true.
Note: An endless loop should be used carefully since if the loop isn’t correctly managed, it might make the program unusable. Following is an example of a while(true) loop:
using namespace std;
int main() {
while (true) {
cout << "Hello LinuxHint\n";
}
return 0;
}
Another example of infinite:
#include <string>
using namespace std;
int main() {
string i;
while (true) {
cout << "Please enter a string: ";
cin >> i;
if (i == "exit") {
break;
}
cout << "The string you entered is: " << i << endl;
}
return 0;
}
The execution starts from the main function where the string type i variable is declared then in an infinite while(true) loop cout statement prints a message as “Please enter a string: “. After this, the user enters the string using cin. It will only end until or unless the user enters the “exit” string, which is defined in the if-statement condition.
Output
Conclusion
Loops are a very essential part of C++ programming. One of the loops is the while(true) loop, which runs infinitely until it was stopped manually or with some statement. Given that they are used for looping a series of instructions an infinite number of times, it is also known as repeating loops. Infinite loops should carefully be employed in the codes as they can break the code.