问题
What is the difference when we declare variable before using in loop and when define variable in loop.
I am talking about this situation
int i;
for(i=0; i<100; i++);
and
for(int i=0; i<100; i++);
回答1:
In the first case it is supposed that variable i will be used also after the loop as for example
int i;
for(i=0; i<100; i++);
printf( "i = %d\n", i );
Nevertheless it would be much better to write the following way
int i = 0;
for( ; i<100; i++);
printf( "i = %d\n", i );
In this case we will get a valid readable code without a need to bother what is done within the loop as for example
int i = 0;
/* some loop used i */
printf( "i = %d\n", i );
That is even if the variable will not be changed (assigned) in the loop or in some other code instead of the loop (usually each code has a tendency to be changed) nevertheless we will get a valid result.
In the second case it is supposed that variable i will be used only within the loop
for(int i=0; i<100; i++);
We need not its value outside the loop. So in this case the life of the variable is limited by the body of the loop. Outside the loop it will be invisible and not alive.
回答2:
In the former case, you can access i outside the for-loop. This can be advantageous if you have a conditional break in your loop, for example:
int i = 0;
for (i = 0; i < 100; i++) {
if (someUnexpectedConditionHappens()) {
break;
}
// do something
}
printf("The loop has been executed %d times", i);
回答3:
It's the "scope". In the second case, you can only use the variable within the for loop. In the first case - in the entire containing block.
回答4:
In the first case, i can be accessed outside the loop within the current block. In C89, you cannot declare variables in the loop so you'll have to stick to this method.
In the second case, i cannot be accessed outside the loop. Declaring variables in the loop is a C99 feature.
回答5:
When you do it before the loop, the variable is then available outside the loop as well. Whereas when you do it inside it, it is a local variable that can only be used inside the loop.
Also, you can declare a variable inside a loop when using C99 standard. But it does not work for example for C90. So be careful with that.
回答6:
In the first case, i is accessible outside the for loop.
In the second case, the scope of i is restricted to the for loop body.
Arguably the second case gives you better program stability since the use of i outside the for loop is often unintentional.
来源:https://stackoverflow.com/questions/31513260/declaration-difference