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

    cybrscot

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

    Rodimus Prime

    #2
    yes.
     
  3. McGordon, Apr 4, 2011
    Last edited: Apr 4, 2011

    macrumors member

    #3
    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

    cybrscot

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

    notjustjay

    #5
    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.
     

Share This Page