Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

cybrscot

macrumors 6502
Original poster
Dec 7, 2010
282
0
Somewhere in Southeast Asia
Is the following basically another way to write an infinite loop?

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

and
Code:
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?
 
Last edited:

McGordon

macrumors member
Dec 28, 2010
63
1
Scotland
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
Code:
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.
 
Last edited:

notjustjay

macrumors 603
Sep 19, 2003
6,056
167
Canada, eh?
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.