0
0
CppHow-ToBeginner · 3 min read

How to Create an Infinite Loop in C++: Simple Guide

In C++, you can create an infinite loop using while(true) or for(;;). These loops run endlessly until you manually stop the program or use a break statement inside the loop.
📐

Syntax

There are two common ways to write an infinite loop in C++:

  • while(true): The condition true always stays true, so the loop never ends.
  • for(;;): This loop has no start, condition, or increment, so it runs forever.
cpp
while(true) {
    // code here runs forever
}

for(;;) {
    // code here runs forever
}
💻

Example

This example shows an infinite loop that prints a message repeatedly. It uses while(true) to keep running.

cpp
#include <iostream>

int main() {
    while(true) {
        std::cout << "This loop runs forever!\n";
        // To avoid flooding the screen, we break after 5 prints
        static int count = 0;
        count++;
        if (count == 5) {
            break; // stop the infinite loop
        }
    }
    std::cout << "Loop stopped after 5 iterations." << std::endl;
    return 0;
}
Output
This loop runs forever! This loop runs forever! This loop runs forever! This loop runs forever! This loop runs forever! Loop stopped after 5 iterations.
⚠️

Common Pitfalls

Infinite loops can cause your program to freeze or crash if you forget to stop them. Common mistakes include:

  • Not including a break or exit condition inside the loop.
  • Using a wrong condition that never becomes false.
  • Causing high CPU usage by running loops without pauses.

Always ensure you have a way to exit or control the loop.

cpp
// Wrong: This loop never stops and can freeze your program
// while(true) {
//     // no break or exit
// }

// Right: Add a break condition
while(true) {
    // some code
    if (some_condition) {
        break; // exit loop
    }
}
📊

Quick Reference

Here is a quick summary of infinite loop syntax in C++:

SyntaxDescription
while(true)Runs the loop forever until broken
for(;;)Infinite loop with no condition or increment
do { ... } while(true);Runs loop body at least once, then repeats forever

Key Takeaways

Use while(true) or for(;;) to create infinite loops in C++.
Always include a way to exit the loop to avoid freezing your program.
Infinite loops run endlessly unless stopped by a break or external action.
Be careful with CPU usage when running infinite loops without pauses.
Test infinite loops with a controlled exit to understand their behavior.