Friday, July 29, 2016

C Basics - Infinite Loop in C

A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.

#include <stdio.h>
 
int main () {

   for( ; ; ) {
      printf("This for loop will run forever.\n");
   }

   return 0;
}

When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but the common method of use is for(;;) construct to signify an infinite loop.

while loop can also be used to create infinite loop. This loop is also called as super loop.

#include <stdio.h>
 
int main () {

   while ( 1 ) {
      printf("This while loop will run forever.\n");
   }

   return 0;
}

You can terminate an infinite loop by pressing Ctrl + C keys.



Related topics:
Loops in C   |   The for Loop in C   |   The while Loop in C   |   The do-while Loop in C   |   Nested Loop in C   |   Loop Control Statements in C   |   The break Statement in C   |   The continue Statement in C   |   The goto Statement in C   |   The return Statement in C

List of topics: C Programming

No comments:

Post a Comment