How Do Infinite Loops Happen in C?
In C programming, there are two scenarios in which a program can enter an infinite loop. These are:
- Deliberate Infinite Loops
- Accidental Infinite Loops
Intentional Infinite Loops
In C programming, deliberate infinite loops are purposefully crafted for applications requiring continuous execution. For instance, servers commonly employ perpetual loops to consistently await incoming client requests, whereas embedded systems might utilize them for real-time sensor monitoring and event processing. This perpetual loop guarantees uninterrupted software operation until explicitly halted.
Unintentional Infinite Loops
In the realm of C programming, inadvertent infinite loops arise from logic flaws within the code. When a loop lacks an exit condition or is improperly structured, it will continue running indefinitely. This situation can result in the program freezing, becoming unresponsive, or utilizing excessive system resources, thereby raising performance issues.
When to use an infinite loop in C programming?
An infinite loop is useful for those applications that accept the user input and generate the output continuously until the user exits from the application manually. In the following situations, this type of loop can be used:
- All the operating systems run in an infinite loop because it does not exist after performing some task. It comes out of an infinite loop only when the user manually shuts down the system.
- All the servers run in an infinite loop because the server responds to all the client requests. It comes out of an indefinite loop only when the administrator shuts down the server manually.
- All the games also run in an infinite loop. The game will accept the user requests until the user exits from the game.
Types of Infinite Loops in C
In C, infinite loops can be built using a variety of loop structures, including while, for, do-while, and goto statements . Each type can be utilized on purpose for tasks that require continuous execution, or they can occur due to logic errors in the code. In C, an infinite while loop continues to execute as long as the condition is true. If the condition remains true or never changes to false, the loop will run indefinitely.
- for loop
- while loop
- do-while loop
- goto statement
- C macros
Now, we will explore these various infinite loops individually.
1) Infinite for loop
In C programming, when the initialization, condition, and increment parts of a for loop are not provided, the loop will execute infinitely as it lacks a beginning point, termination condition, or progress update.
Syntax
It has the following syntax:
for( ; ; )
{
// Code that runs infinitely.
}
In this syntax,
- for: It starts a for loop in C.
- (; ;): It represents an empty initialization, condition, and increment, causing the loop to run indefinitely.
- {: It opens the block containing statements to repeat.
- }: It ends the loop's code block.
Infinite For Loop Example in C
Let's consider a scenario to demonstrate the infinite for loop in the C programming language.
Example
#include <stdio.h>
int main() //main function
{
int record _Count = 1;
for (;;)
{
// No initialization, condition, or increment and code runs infinitely.
printf("It is an Infinite for loop iteration: %d\n", record _Count);
record _Count ++;
}
return 0;
}
Output:
It is an Infinite for loop iteration: 1
It is an Infinite for loop iteration: 2
It is an Infinite for loop iteration: 3
It is an Infinite for loop iteration: 4
Explanation:
In this instance, the for(;;) loop functions as an infinite loop that continuously displays the count. As there is no specified condition, it will iterate endlessly.
2) Infinite While Loop
In C programming, a while loop that runs infinitely will continue executing as long as the condition stays true. If the condition persists in being true or never transitions to false, the loop will run endlessly.
Syntax
It has the following syntax:
while (1)
{
// Code that will continue to execute
}
Infinite While Loop Example in C
Let's consider a scenario to demonstrate the infinite while loop in the C programming language.
Example
#include <stdio.h>
int main() //main function
{
while (1)
{
printf("It is an infinite while loop.\n");
}
return 0; // This line can never be reached.
}
Output:
It is an infinite while loop.
It is an infinite while loop.
It is an infinite while loop.
It is an infinite while loop.
Explanation:
In this instance, the while(1) loop runs indefinitely as the condition is perpetually true, causing it to repeatedly execute the identical block of code.
3) Infinite do-while loop
In C programming, the typical do-while loop executes a minimum of one time, while a perpetual do-while loop runs endlessly as long as the loop condition remains true. This situation arises when the condition is constantly set to true (e.g., 1) or when the variables involved in the condition are never altered to turn it false.
Syntax
It has the following syntax:
do
{ // Code block to execute infinitely.
}
while (1); // Always true, so loop never ends.
- The do with { } tag encloses a block of code that will be executed repeatedly.
- while (1); tests the condition after each iteration, and because 1 is always true, the loop runs indefinitely.
Infinite do-while Loop Example in C
Let's consider an example to demonstrate the endless do-while loop in the C programming language.
Example
#include <stdio.h>
int main() //main function
{
int record_Count = 0;
do
{
printf("It is an infinite do-while loop iteration count: %d\n", record_Count);
record_Count ++;
} while (1);
return 0; // This line can never execute.
}
Output:
It is an infinite do-while loop iteration count: 0
It is an infinite do-while loop iteration count: 1
It is an infinite do-while loop iteration count: 2
It is an infinite do-while loop iteration count: 3
Explanation:
In this instance, the do {... } while(1); loop runs endlessly and consistently performs at least one iteration. The condition is evaluated after each cycle and continues to be true.
4) Infinite loop in C using a goto statement
In the realm of C programming, the goto statement provides a means to jump directly to a specified labeled section within our code. Although it can be beneficial for breaking out of nested loops or managing specific error scenarios, it is typically shunned due to its potential to complicate program comprehension and upkeep.
When employing the goto statement, there is a risk of inadvertently or purposely creating an endless loop if the program continuously returns to the same label without a termination condition.
Syntax
It has the following syntax:
label:
// Code block
goto label; // Jumps back to 'label' unconditionally.
Infinite loop in goto statement Example in C
Let's consider a scenario to demonstrate an endless loop caused by the goto statement in C programming.
Example
#include <stdio.h>
int main() //main function
{
int record_Count = 1;
loop:
printf("It is an infinite loop using goto statement: %d\n", record_Count);
record _Count ++;
if (record _Count <= 5)
goto loop;
//Jumps to the 'loop' label until the count is greater than 5.
return 0;
}
Output:
It is an infinite loop using goto statement: 1
It is an infinite loop using goto statement: 2
It is an infinite loop using goto statement: 3
It is an infinite loop using goto statement: 4
It is an infinite loop using goto statement: 5
Explanation:
In C programming, the goto statement repeatedly jumps to a specified label, causing an endless loop where program control cycles back to that label.
5) Infinite loops and macros in C
In the realm of C programming, macros serve as preprocessor directives enabling the creation of reusable code blocks. This enhances code clarity by reducing redundancy, thereby simplifying maintenance tasks, particularly in scenarios where repetitive logic is essential.
We have the ability to establish an endless loop by converting a macro into a loop format, like while(1), that executes endlessly.
Syntax
It has the following syntax:
#define INFINITE_LOOP_MACRO while(1) { \* Loop body */ }
In this syntax,
- The #define is a preprocessor directive that defines a macro.
- INFINITELOOPMACRO is the macro name that we will be use in our code.
- The macro body (while(1) {... }) is an infinite loop that expands whenever the macro name appears in our code.
Infinite Loop in C Macro Example
Let's consider a scenario to demonstrate the concept of an endless loop within a macro.
Example
#include <stdio.h>
#define INFINITE_LOOP_MACRO while(1) { printf("Infinite Loop\n"); }
int main() //main function
{
INFINITE_LOOP_MACRO;
// Expands into the infinite loop.
printf("Code after infinite loop\n");
// It can never be executed
return 0;
}
Output:
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop
Explanation:
In this instance, the #define LOOP while(1){...} establishes an endless loop, persistently executing the loop's contents without halting.