Infinite for loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vensriram
    New Member
    • Aug 2010
    • 48

    Infinite for loop

    Code:
    for(;;)
    {
    }
    is an infinite loop

    but whether it can be made finite by modifying it into
    Code:
    i = 5;
    for(;;)
    {
    printf("%d", i++)
    if(i>10)
    break;
    }
    My opinion is the above code will not be infinite and the loop will come to an end after i takes the value 11. Is it correct?
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #2
    Yes and it will print 567891011

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Your loop is still an infinite loop.

      The fact you broke out of the loop does not make it finite.

      In this case, the loop should not have been infinite to start with:

      Code:
      i = 5; 
      for(;i<=10;++i) 
      { 
      printf("%d", i) 
      }
      A break is usually a sign of a poorly desinged loop. That is, the code that regulates the loop should not appear inside the loop. This is why the for statement was put into C in the first place.

      Comment

      Working...