0

Is this acceptable by all C Standards?

for (int i=0; i<n; i++) {
    // do stuff
}

Or should I write it like this just to be sure it works everywhere?

int i;
for (i=0; i<n; i++) {
    // do stuff
}
2
  • 1
    No. You need to write second one. Commented Jan 21, 2016 at 18:17
  • There is only one C standard, which is currently ISO 9899:2011. And that accepts this very well. And the second version has different semantics. Commented Jan 21, 2016 at 18:46

1 Answer 1

2

No, it's valid since C99 only. If you want your code to be valid under old standards use

int i;
for (i = 0 ; i < n ; i++)

And also, read this comment by @JoachimPileborg it complements well this answer.

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

3 Comments

It might be worth noting that before C99 the variable need to be declared in the declaration block first in the function as well. One can't simply declare the loop count variable just before the loop (unless the loop is the first non-declaration statement in the function).
This has different semantics, as the scope of i is now that of the enclosing block, not just the for loop.
I sometimes break from a loop and use the value of i after the loop to see if it completed naturally. But if i has gone out of scope that is not possible.

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.