3

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?
}
9
  • 6
    It's perfectly legal. Have you tried it? Commented Jan 13, 2014 at 2:19
  • yes, it somehow doesn't work, maybe i'm doing something wrong... But the purpose of the question was to ask if it is a good practice to do so, if it's possible. Commented Jan 13, 2014 at 2:20
  • 4
    What doesn't work? Maybe update your question with what seems to be unexpected about the resulting behaviour. Commented Jan 13, 2014 at 2:21
  • It's legal, but it is meant exceptional processing probably. Commented Jan 13, 2014 at 2:22
  • OK, thanks, I'll try to debug a bit more time, if I don't manage to get it working I'll post the broken code. Commented Jan 13, 2014 at 2:25

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.