PDA

View Full Version : C Programming Infinite Loop?




cybrscot
Apr 4, 2011, 10:12 AM
Is the following basically another way to write an infinite loop?

for ( i=0; i<20; i++)
i--;


and
for (i=0; i<20; i*20)
printf("modicication...");



It looks like it to me, because the body decrements the 0 to -1, then the third expression increments -1 back to 0, and this keeps going on and on.

The second example will also continue to print also, because i=0, and 0*anything is always 0. Both infinite loops?



Rodimus Prime
Apr 4, 2011, 10:22 AM
yes.

McGordon
Apr 4, 2011, 10:26 AM
Well, yes it will be an infinite loop, but I wouldn't say it was the way to write one deliberately. It's more like something that would happen accidentally when you wanted to loop 20 times, but accidentally altered the loop control variable, i, inside the loop.

Edit: You added the 2nd loop while I was replying


and
for (i=0; i<20; i*20)
printf("modicication...");



It looks like it to me, because the body decrements the 0 to -1, then the third expression increments -1 back to 0, and this keeps going on and on.

The second example will also continue to print also, because i=0, and 0*anything is always 0. Both infinite loops?

It is also an infinite loop, but not for the reason you state. You are calculating i*20, but not storing it anywhere, so I will stay 0. If you'd started with i=1 and had that i*20, i would still stay at 1 because you're not increasing it anywhere.

cybrscot
Apr 4, 2011, 10:28 AM
Cool, thanks to both of you.

notjustjay
Apr 4, 2011, 10:46 AM
If you really want an infinite loop, there are a few better ways to write it:

while(1)
{
// your loop stuff
}

or

for( ; ; )
{
// your loop stuff
}

"Better" in the sense that anyone reading the code can see immediately that the loop is intended to go forever. Your first example works as an infinite loop but at first glance it looks more like a loop that's intended to work 20 times except for the decrement, which will cause programmers to say "OK, is that a bug? Or was that intentional?" And your second example likewise makes people stop and think "OK, wait, what's that doing there? How does that work?" which is not what you want when writing good clean code.