在整个网络上,代码示例都有如下所示的for循环:
for(int i = 0; i < 5; i++)
Run Code Online (Sandbox Code Playgroud)
我使用以下格式:
for(int i = 0; i != 5; ++i)
Run Code Online (Sandbox Code Playgroud)
我这样做是因为我认为它更有效率,但这在大多数情况下真的很重要吗?
我很清楚在C++中
int someValue = i++;
array[i++] = otherValue;
Run Code Online (Sandbox Code Playgroud)
与...相比有不同的效果
int someValue = ++i;
array[++i] = otherValue;
Run Code Online (Sandbox Code Playgroud)
但每隔一段时间我就会在for循环中看到带有前缀增量的语句,或者仅仅是它们自己的语句:
for( int i = 0; i < count; ++i ) {
//do stuff
}
Run Code Online (Sandbox Code Playgroud)
要么
for( int i = 0; i < count; ) {
//do some stuff;
if( condition ) {
++i;
} else {
i += 4;
}
}
Run Code Online (Sandbox Code Playgroud)
在后两种情况下,++i看起来像是试图生成看起来很聪明的代码.我在监督什么吗?是否有理由使用++i而不是i++后两种情况?