Also, in the C language (before C99), you could
not declare variables
after a statement, nor inside of a
for
loop. So this would have been the only way to go:
1 2 3 4 5 6 7 8 9 10
|
void my_function(void)
{
int i; /* <-- variable declarations must come first! */
/* possibly more statements here */
for (i = 0; i < 10; i++) {
/* ... */
}
}
|
...and therefore you'll still find many examples that do it that way.
Declaring the loop counter variable right inside the
for
statement is a "convenience" feature that results in cleaner/shorter code, as you don't need a separate variable declaration in front of the loop.
Also, it limits the scope of the loop counter variable to the loop, which makes sense most of the time.
(BTW: If you need to know the "final" value of the loop counter
after the loop has finished, e.g. because your loop may
break
early, then you still need to declare the counter variable outside of the loop)