for( ... ) 循环索引声明样式
Maybe之间在代码方面是否有任何区别
int i = 0;
for ( i = 0 ; i < n ; i++ )
{
}
:和
for ( int i = 0 ; i < n ; i++ )
{
}
如果存在更多循环并且它们都使用相同的索引,则
?另外,第一个版本是否相当于:
int i = 0;
for ( ; i < n ; i++ )
{
}
我知道优化器应该足够聪明,至少可以生成相同的代码,但是理论上有什么区别吗?
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 optimizer should be smart enough to generate the same code at least, but is there theoretically any difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在第一种和第三种情况下,
int i
的范围超出了 for 循环。在第二种情况下,作用域是for
循环,如果您想稍后使用它,则必须重新声明i
。是的,仅当您不在前两行之间放置任何内容时,第一个版本才相当于第三个版本。如果您在两者之间添加一些代码,那么所有的赌注都会被取消。
In first and third case, the scope of
int i
is beyond the for loop. In second case, scope is with thefor
loop and you will have to re-declarei
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.
“i”的范围不同。
在情况 1 中,您可以在循环外部访问它,而在情况 2 中,您只能在循环内部访问它。退出循环后它就不再存在了。
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.
第一个和第三个版本几乎相同;略有不同的是,
i = 0
在第一个版本中被分配,而在第三个版本中初始化。 (对于用户定义的数据类型,这有时会产生很大的差异)。第二个版本在功能上是相同的;然而,
i
的作用域位于for
循环内。因此,一旦{}
完成,就无法访问i
。我更喜欢这个版本。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 withinfor
loop. Soi
cannot be accessed once the{}
is finished. I prefer this version.好吧,我明白了为什么我们在循环外使用索引声明。
显然我们的solaris编译器会给出如下代码的编译错误:
错误是:
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:
The error is:
第一和第三在所有方面都是相同的。
第二个在功能上是相同的,但仅将
i
的范围(使用)限制在 for 循环内。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.