问题
I see this in a lot of game engine code. Is this supposed to be faster than if you were to declare it in the for loop body? Also this is followed by many other for loops, each of them using the same variable.
int i;
for(i=0; i<count; ++i)
{
}
vs
for(int i=0; i<count; ++i)
{
}
Btw I never do this myself, just curious about the idea behind it, since apart from performance I don't know why anyone would do this.
回答1:
The first way is probably the C way, the OLD OLD C way, where the second version wasn't valid. Use the second way, scope the variables tight as possible.
回答2:
What's the benefit of declaring for the loop index variable outside the loop?
In former case you can access i last value outside loop. Naive developers say that value will be the value of count. But sample this
int i;
for(i = 0; i < count; ++i)
{
if (i == 2)
break;
//Loop Logic
}
In such case i will be = 2 or < 2 but what if count is > 2.
However in latter one i becomes out of scope as soon as loop ends
回答3:
Originally, in K&R C, if you had a for statement such as
for (int i = 1; ...
you couldn't later in the same method (or {} scope) again say
for (int i = 1; ...
or you would get a "duplicate symbol" error.
So if one wanted to reuse the same loop variable then they'd declare it outside the loops.
That "feature" of C is long gone, but still, if one wants to break out of a loop and preserve the loop index then it's necessary to declare the loop variable outside the for statement:
int i;
for (i = 1; ...
do stuff;
if (something) break;
}
x = y[i];
回答4:
K&R C didn't accept the second style.
One advantage of the first style is that you can access 'i' after the loop, which might be important if you're searching for a particular index.
The advantage of the second is tighter scoping, which is always a good thing. You can't get your 'i's mixed up.
回答5:
There is at least one compiler (an older version of MSVC) which leaked the definition of the int i in for(int i = 0; i < max; ++i) { ... } beyond the end of the loop. The standard, meanwhile, said that its scope is limited to the for loop itself. If you where compiling in multiple compilers, one of which leaked the definition, and the other of which didn't, you could easily run into problems if you redeclared the variable later in the same body of code.
So I could see someone deciding to make code that would get the same errors in both the standards-compliant, and non-standards compliant compilers, by putting the variable declaration outside of the loop.
Now, another theory is that the programmer wanted access to the value of the iteration variable after the loop ends. Another possibility is that the team or coder thought that putting variable declaration on its own line was good style.
来源:https://stackoverflow.com/questions/13150001/whats-the-benefit-of-declaring-for-the-loop-index-variable-outside-the-loop