Tuesday 8 November 2011

Other Causes of Infinite Loops in C programming

Other Causes of Infinite Loops

There are many other possible causes for infinite loops. Consider the following code fragment:
unsigned int nbr;
for( nbr = 10 ; nbr >= 0 ; -- nbr )
{
/* do something */
}

This fragment of code will run forever, because nbr, as an unsigned variable, will always be greater than or
equal to zero because, by definition, an unsigned variable can never be negative. When nbr reaches zero and
is decremented, the result is undefined. In practice, it will become a very large positive number. Printing the
value of the variable nbr inside the loop would lead you to this unusual behavior.

Yet another cause of infinite loops can be while loops in which the condition never becomes false. Here’s
an example:
int main()
{
int a = 7;
while( a < 10 )
{
++a;
a /= 2;
}
return( 0 );
}

Although the variable a is being incremented after every iteration of the loop, it is also being halved. With
the variable being initially set to 7, it will be incremented to 8, then halved to 4. It will never climb as high
as 10, and the loop will never terminate.

No comments:

Post a Comment