Menu
Coddy logo textTech

Infinite Loops

Part of the Fundamentals section of Coddy's C++ journey — lesson 49 of 74.

An infinite loop is a loop that never stops because its condition is always true, or there's no condition to stop it. While sometimes useful, they often lead to programs freezing or crashing. It's like a dog chasing its tail forever - it just keeps going and going without end.

Here's a simple example of an infinite loop using a while loop:

while (true) {
    std::cout << "This will print forever!" << std::endl;
}

In this case, the condition is always true, so the loop will run indefinitely.

You can also create an infinite loop with a for loop by leaving out the condition:

for (;;) {
    std::cout << "This will also print forever!" << std::endl;
}

Here, there's no condition to check, so the loop has no reason to stop.

Infinite loops can be useful in some cases, like in servers that need to keep running until manually stopped. However, in most cases, they are problematic. To stop an infinite loop, you usually have to force-quit the program (e.g., by pressing Ctrl+C in the terminal).

Cheat sheet

An infinite loop is a loop that never stops because its condition is always true or there's no condition to stop it.

Infinite loop with while:

while (true) {
    std::cout << "This will print forever!" << std::endl;
}

Infinite loop with for (no condition):

for (;;) {
    std::cout << "This will also print forever!" << std::endl;
}

To stop an infinite loop, force-quit the program (e.g., Ctrl+C in terminal).

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals