Jun 27, 2014

C Programming #27: Loop - infinite

Infinite loops are loops that run forever, condition in such loop is such that it is always true. If we do not handle loop counter and condition properly we might end up in infinite loop. In some cases we totally need to avoid infinite loop, but in few cases like Embedded System we need infinite loop.


Below are few examples of infinite loops.

Example 1
while(1) {
  printf("Forever\n");
}
Explanation:
condition is 1 which is true in C, hence the loop will run forever.

Example 2
do {
  printf("Forever\n");
}while(1);
Explanation:
condition is 1 which is true in C, hence the loop will run forever.

Example 3
for(;;) {
  printf("Forever\n");
}
Explanation:
All the 3 parts initialize_counter, condition, change_condition are absent, In such case C evaluates all 3 parts to true. Since condition is true always, this is a infinite loop.

Example 4

unsigned char i;

for(i = 255; i >= 0; i--) {
   printf("%d\n", i);
}

Unsigned integer cannot have negative values. The condition i >= 0 is waiting for i to become -ve to exit the loop, which never occur, hence the loop is infinite.

What will be the value of i when subtracted 1 from it ?
Since i is unsigned character, subtracting 1 will cause underflow and i will get maximum value which is 255.

How to debug infinite loop ?
Print the loop counter and loop condition in the loop. This is will give idea of what is going. wrong.

Links

Quiz - Not written Yet
Next Article -  C Programming #28: Decision Making - goto
Previous Article - C Programming #26: Loop - nested 
All Article - C Programming

No comments :

Post a Comment