开发者

for( ... ) loop index declaration style [closed]

开发者 https://www.devze.com 2023-04-05 14:07 出处:网络
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time,or an extraordinarily narrow situation that is not generally applic
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 10 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号