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 In this case, the condition is always In C++, the
while loop:while (true) {
std::cout << "This will print forever!" << std::endl;
}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;
}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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else