0
0
CHow-ToBeginner · 3 min read

How to Create an Infinite Loop in C: Simple Syntax and Examples

In C, you can create an infinite loop using while(1), for(;;), or do { } while(1). These loops run endlessly because their conditions always evaluate to true.
📐

Syntax

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

  • while(1): Runs the loop as long as the condition 1 (true) is met.
  • for(;;): Omits all three parts of the for loop, so it loops forever.
  • do { ... } while(1): Executes the loop body first, then checks the condition which is always true.
c
while(1) {
    // code here
}

for(;;) {
    // code here
}

do {
    // code here
} while(1);
💻

Example

This example shows an infinite loop using while(1) that prints a message repeatedly.

c
#include <stdio.h>

int main() {
    while(1) {
        printf("This loop runs forever.\n");
        break; // Remove this line to make it truly infinite
    }
    return 0;
}
Output
This loop runs forever.
⚠️

Common Pitfalls

Common mistakes when creating infinite loops include:

  • Forgetting to include a way to exit the loop if needed, which can freeze your program.
  • Using a condition that eventually becomes false, so the loop is not truly infinite.
  • Misplacing semicolons that can create empty loops unintentionally.

Example of a wrong infinite loop and the correct way:

c
// Wrong: semicolon ends the loop immediately
while(1);

// Correct: loop body inside braces
while(1) {
    // code here
}
📊

Quick Reference

Summary tips for infinite loops in C:

  • Use while(1) or for(;;) for simple infinite loops.
  • Remember to include a break condition if you want to stop the loop later.
  • Check for accidental semicolons after loop statements.

Key Takeaways

Use while(1) or for(;;) to create infinite loops in C.
Infinite loops run endlessly because their conditions always evaluate to true.
Avoid accidental semicolons that create empty loops.
Include a break condition if you want to stop the loop safely.
Test loops carefully to prevent freezing your program.