Is there any difference code-wise between:
int i = 0;
for ( i = 0 ; i < n ; i++ )
{
}
and
for ( int i = 0 ; i < n ; i++ )
{
}
Maybe if there are more loops and they all use the same index?
Also, is the first version equivalent to:
int i = 0;
for ( ; i < n ; i++ )
{
}
I know the opt开发者_StackOverflowimizer should be smart enough to generate the same code at least, but is there theoretically any difference?
In first and third case, the scope of int i
is beyond the for loop. In second case, scope is with the for
loop and you will have to re-declare i
if you want to use it later.
And yes, the first version is equivalent to third version only if you don't put anything between the first two lines. If you add some code in between, then all bets are off.
The scope of 'i' is different. In case 1, you can access it outside the loop while in case 2 you can only access it inside the loop. It won't exist anymore after you get out of the loop.
1st and 3rd versions are almost same; with the little difference that i = 0
is assigned in 1st version and initialized in the 3rd version. (For user defined data types, this can make a big difference sometimes).
2nd version is functionality-wise same; however i
is scoped within for
loop. So i
cannot be accessed once the {}
is finished. I prefer this version.
Ok so I figured out why we were using the index declaration outside the loop.
Apparently our solaris compiler will give a compilation error for code like:
for ( int i = 0 ; ; );
for ( int i = 0 ; ; );
The error is:
Error: multiple declaration for i.
first and third are the same in all respects.
Second is functionally same, but restricts the scope (of usage) of i
within that for loop only.
The first version and the third are the same.
The second version as one difference from the other: i only live in the loop scope.
精彩评论