Infinite loop in C

An infinite loop is one that does not terminate the loop from its looping condition. An infinite loop can be needed in programming in some special conditions or some loop can fall into infinite loops when the exit condition becomes false forever.

Infinite for loop in C

For loop has a condition to terminate the loop. This condition can be left as blank. We can also skip initialization statement and repeat statements. These are optional and can be left as blank.

For loop syntax:
for (
  <initial statement(s)>;
  <Condition expression>;
  <Repeat step(s)>
  )
{
  <Loop statement(s)>;
}

Infinite For loop:
for(;;);

for(;;)
{
}

Infinite while loop in C

While loop While loop has a condition statement. This expression is mandatory and cannot be skipped. So we need to place a true condition here. We can place “TRUE”, “1”, “1==1” etc any of the statement.

While loop syntax:
while (<Condition expression>)
{
  <Loop statement(s)>;
}
Infinite While loop:
while(1);

while(1)
{
}

Infinite do-while loop in C

Do While loop While loop has a condition like while loop. We can make place the same always true statement to make an infinite loop.

Do-While loop syntax:
do
{
  <Loop statement(s)>;

}while (<Condition expression>);

Infinite Do-While loop:

do {
}while(1);

Long running loops

It is recommended to put some delay in each loop. Otherwise task may take up all CPU cycles and may hang up the system. This is needed if programmer is polling for some condition to happen. A sleep statement will release the task to scheduler and other task will be able to run properly.

While Loop:

while(1)
{
  Sleep(1);
}

Do-While Loop:

do
{
  Sleep(1);
}
while(1);
 
For Loop:

for(;;)
{
  Sleep(1);
}

Debug infinite loops

A program can enter into an infinite loop and the program can loop forever. This type of issue may not happen very often and some rare situations can bring this type of condition. However, these types of issues are easy to debug. We should break in a statement and put the break in the condition check. We need to find out why the condition is not becoming false to root cause further.

About our authors: Team EQA

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

#