C Programming Infinite Loop?

Discussion in 'Mac Programming' started by cybrscot, Apr 4, 2011.

  1. cybrscot, Apr 4, 2011
    Last edited: Apr 4, 2011

    macrumors 6502


    Is the following basically another way to write an infinite loop?

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

    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?
  2. macrumors G4

    Rodimus Prime

  3. McGordon, Apr 4, 2011
    Last edited: Apr 4, 2011

    macrumors member

    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

    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.
  4. macrumors 6502


    Cool, thanks to both of you.
  5. macrumors 603


    If you really want an infinite loop, there are a few better ways to write it:

    // your loop stuff


    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.

Share This Page