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 omitting the initialization, condition, and increment expressions:
for (;;) {
    std::cout << "This will also print forever!" << std::endl;
}
In C++, the for loop syntax requires two semicolons, but the three expressions (initialization, condition, and increment) are optional. By leaving them empty, there is 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).

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