Dima Knivets
Dima Knivets

Reputation: 2528

Increment internal counter variable inside for loop

So, that's the question: can I increment the i variable inside for loop?:

for(int i = 0; i < 1000; i++)
{
    i++; // is this legal? if not what is the alternative?
}

Upvotes: 3

Views: 4250

Answers (2)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158459

If we look at the C99 draft standard it says the following about the for loop in section 6.8.5.3 The for statement:

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.137)

So if we parse this text your for loop will be roughly equivalent to the following:

{
   int i = 0 ;  // clause 1
   while( i < 1000 ) //expression 2
   {
         i++ ; // statement

         i++ ; // expression 3
   }      
}

which is valid code but you would probably not write the code this way if you translated it out by hand.

Upvotes: 3

LoztInSpace
LoztInSpace

Reputation: 5697

Absolutely legal but not very intuitive.

Consider using a while loop instead if you need to manipulate your looping in this way (it's just a code clarity thing, not a legal thing).

Upvotes: 4

Related Questions