Where did you get this idea?
The C11 draft, section 6.8.5 (1), says:
iteration-statement:
while ( expression ) statement
do statement while ( expression ) ;
for ( expressionopt ; expressionopt ; expressionopt ) statement
for ( declaration expressionopt ; expressionopt ) statement
That last form makes it pretty clear that a declaration is still allowed in the first clause of the for
statement.
[Update]
Note that declaration is something like int i = 0 ;
. That is, it includes the semi-colon (see section 6.7). So for (int i = 0 ; i < 10 ; ++i)
is definitely allowed by C11.
[Update 2]
As for when to use which, that is a matter of opinion. My opinion is that you should embed the declaration whenever you can, because it makes the code easier to read.
If I am reading your code and I see:
for (int i = 0 ; i < 10 ; ++i)
...
...then I know you are not relying on the value of i
after the loop terminates, because it is no longer in scope.
If I see:
int i;
for (i = 0 ; i < 10 ; ++i)
...
...then I expect you to use the value of i
later; e.g. maybe you break
early and want to know what i
was when that happened. If I do not see you use i
later, I will probably wonder what you were thinking and/or what I am missing.
As usual, readability is the most important metric. Of course, what qualifies as "readable" is a matter of opinion.
No comments:
Post a Comment