C Infinite Loop

An infinite loop in C is a loop that runs indefinitely because the condition that controls the loop never becomes false. This type of loop can be useful in certain situations, such as when waiting for a user input or handling continuous processes.

1. Infinite Loop Syntax

An infinite loop can be created using any of the loop structures: for, while, or do-while. The key to creating an infinite loop is ensuring that the loop condition is always true or that no condition is checked (in the case of the for loop).

Syntax:

                        
// Using for loop
for (;;) {
    // infinite loop code
}
        
// Using while loop
    while (1) {
    // infinite loop code
}
        
    // Using do-while loop
        do {
    // infinite loop code
} while (1);
                        
                    

Example:

                        
#include <stdio.h>
int main() 
{
    int i = 0;
    // Infinite loop using while
    while (1) {
        printf("i = %d\n", i);
        i++;
        if (i == 5) {
         break; // Breaking the loop after 5 iterations
        }
    }
     return 0;
}
                        
                    

Output:

i = 0
i = 1
i = 2
i = 3
i = 4

2. Key Points of Infinite Loops

3. Common Use Cases for Infinite Loops

4. Exiting an Infinite Loop

To exit an infinite loop, you can use control statements such as:

5. Example of Using a Break Statement

The break statement can be used to exit an infinite loop after a certain condition is met.

                        
#include <stdio.h>
int main()
{
  int i = 0;
  while (1) {
     printf("i = %d\n", i);
     i++;
     if (i == 5) {
        break; // Exit the loop after 5 iterations
     }
    }
return 0;
}
                        
                    

Output:

i = 0
i = 1
i = 2
i = 3
i = 4

6. Key Considerations