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:
for (;;) {
// Code to execute indefinitely
}
Explanation of Syntax:
- The
forloop does not contain an initialization, condition, or increment/decrement. - Since there is no condition, it is always considered
true, causing the loop to run indefinitely. - To stop the loop, we can use a
breakstatement 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
#include <stdio.h>
int main() {
for (;;) {
printf("This loop will run forever!\\n");
}
return 0;
}
Explanation:
- The loop does not have an exit condition, so it executes forever.
- The
printf()statement runs continuously, printing the message repeatedly. - The program must be stopped manually using
Ctrl + Cin 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
#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:
- The loop runs indefinitely because there is no condition.
- The
countvariable is incremented in each iteration. - When
countreaches 5, thebreakstatement 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:
- The syntax of an infinite
forloop. - An example where the loop runs indefinitely.
- How to use a
breakstatement 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.
