1

I encountered a strange FOR LOOP question in the book. Here is the code for the loop -

#include<stdio.h>

int main()
{
int i=1,j=1;
for(;;)
  {
    if(i>5)
        break;
    else
        j+=i;
    printf("%d\n",j);
    i+=j;
  }
return 0;
}

The program prints 2 & 5 as the output. Now could anyone please explain how this for loop is executing?

Pranav Jituri
  • 823
  • 1
  • 11
  • 25
  • 1
    You could use a debugger to find out how this executes. – Oliver Charlesworth Dec 24 '13 at 14:46
  • You could also use a search engine. http://en.wikipedia.org/wiki/For_loop#Use_as_infinite_loops and http://en.wikipedia.org/wiki/C_syntax#Iteration_statements ("Any of the three expressions in the for loop may be omitted") – Karoly Horvath Dec 24 '13 at 14:48

3 Answers3

2

That for loop is a classic idiom for a non-terminating loop. It's what you use when you want a loop that never terminates, or whose termination is controlled by control flow statements inside the loop. The latter is the case here.

for(;;)

All parts of the for loop are empty. They key to understanding why it is a non-terminating loop is the empty controlling expression in the for statement.

The standard (6.8.5.3 The for statement) says, with my emphasis:

The statement

for ( clause-1 ; expression-2 ; expression-3 ) statement

behaves as follows: The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body. The expression expression-3 is evaluated as a void expression after each execution of the loop body. If clause-1 is a declaration, the scope of any identifiers it declares is the remainder of the declaration and the entire loop, including the other two expressions; it is reached in the order of execution before the first evaluation of the controlling expression. If clause-1 is an expression, it is evaluated as a void expression before the first evaluation of the controlling expression.158)

Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.

And this means that your loop will never terminate due to the controlling expression part of the for statement.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
2
for(;;)

is a for loop which performs no initialisation, has no exit condition and performs no post-action.

It will loop forever unless code inside the loop contains a condition that can result in break being called.

Your loop is equivalent to

int i,j;
for(i=1, j=1 ;i<=5 ;i+=j) {
    j+=i;
    printf("%d\n",j);
}
simonc
  • 41,632
  • 12
  • 85
  • 103
2

for(;;) is equivalent to while(true) (or while(1) in old-school C), both of whose terminations are only controlled by the statements inside them.


Edit: To rehash a couple of old jokes (borrowed from here):

  1. Don't use for (;;) {} — it makes the statement cry.
  2. Unless, of course, you #define EVER ;;.
Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174