Tuesday 8 November 2011

Infinite Loops in C programming

When your program is in an infinite loop, it is executing a block of code an infinite number of times. This action, of course, is probably not what the programmer intended. The programmer has in some way caused the condition that keeps the program in the loop to never be false or, alternatively, has caused the condition
that would make the program leave the loop to never be true. Look at a few examples of infinite loops:
/* initialize a double dimension array */
for( a = 0 ; a < 10 ; ++ a )
{
for( b = 0 ; b < 10 ; ++ a )
{
array[ a ][ b ] = 0;
}
}

The problem here is that, due to a mistake the programmer made (probably typographical in nature), the
second loop, which can end only when the variable b is incremented to 10, never increments the variable b!
The third part of the second for loop increments a—the wrong variable. This block of code will run forever,
because b will always be less than 10.

How are you to catch such an error? Unless you notice that the variable b is never being incremented by
reviewing the code, you might never catch the error. Inserting the statement

printf(“ %d %d %d\n” , a , b , array[ a ][ b ] );

inside the brace of the second for loop is one action you might take while attempting to debug the code. You
might expect the output from this code fragment to resemble this:
0 0 0
0 1 0
(and eventually reaching)
9 9 0
But what you would really see as output is this:
0 0 0
1 0 0
2 0 0
...
You would have a never-ending sequence, with the first number continually getting larger. Printing the
variables in this fashion not only will help you catch this bug, but it also will let you know if the array did
not contain the values expected. This error could conceivably be very difficult to detect otherwise! This
technique of printing the contents of variables will be used again.

No comments:

Post a Comment