Infinite For Loop in C

An infinite loop is a loop that never terminates unless explicitly stopped by a break statement or an external intervention. In C, an infinite for loop occurs when the loop condition never evaluates to false.

In this tutorial, you will learn the syntax of an infinite for loop in C and how it behaves with practical examples.


Syntax of an Infinite For Loop

An infinite for loop can be created by omitting the loop condition, as shown below:

</>
Copy
for (;;) {
    // Code to execute indefinitely
}

Explanation of Syntax:

  1. The for loop does not contain an initialization, condition, or increment/decrement.
  2. Since there is no condition, it is always considered true, causing the loop to run indefinitely.
  3. To stop the loop, we can use a break statement inside the loop or terminate the program externally.

Examples of Infinite For Loop

1. Printing a Message Indefinitely using Infinite For Loop

In this example, we will print a message continuously using an infinite for loop.

main.c

</>
Copy
#include <stdio.h>

int main() {
    for (;;) {
        printf("This loop will run forever!\\n");
    }
    
    return 0;
}

Explanation:

  1. The loop does not have an exit condition, so it executes forever.
  2. The printf() statement runs continuously, printing the message repeatedly.
  3. The program must be stopped manually using Ctrl + C in the terminal.

Output:

This loop will run forever!
This loop will run forever!
This loop will run forever!
...

2. Infinite For Loop with a Break Condition

We can use a break statement to exit an infinite loop when a certain condition is met.

main.c

</>
Copy
#include <stdio.h>

int main() {
    int count = 0;

    for (;;) {
        printf("Iteration %d\\n", count);
        count++;

        if (count == 5) {
            break;  // Exit loop when count reaches 5
        }
    }
    
    return 0;
}

Explanation:

  1. The loop runs indefinitely because there is no condition.
  2. The count variable is incremented in each iteration.
  3. When count reaches 5, the break statement exits the loop.

Output:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4

Conclusion

In this tutorial, we learned about infinite for loops in C, including:

  1. The syntax of an infinite for loop.
  2. An example where the loop runs indefinitely.
  3. How to use a break statement to exit an infinite loop.

Infinite loops are useful in cases such as background processes, event handling, and server execution, but they should be used with caution to avoid unintended program freezes.