C++

Understanding while(true) Loop in C++

In C++ with the use of loops, a program can carry out a series of instructions repeatedly up until a certain condition is fulfilled. In C++, there are three different forms of loops: for, while, and do-while. With some C++ example programs, this tutorial post will help learners to understand the while(true) loop.

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:

while (true) {

  //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:

#include <iostream>

using namespace std;

int main() {

    while (true) {

        cout << "Hello LinuxHint\n";

    }

    return 0;

}

Another example of infinite:

#include <iostream>

#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.

About the author

Kaynat Asif

My passion to research new technologies has brought me here to write for the LinuxHint. My major focus is to write in C, C++, and other Computer Science related fields. My aim is to share my knowledge with other people.