为什么在语句中的其他地方不使用值的情况下使用++ i而不是i ++? [英] Why use ++i instead of i++ in cases where the value is not used anywhere else in the statement?
问题描述
我很清楚,在C ++中
I'm well aware that in C++
int someValue = i++;
array[i++] = otherValue;
与
int someValue = ++i;
array[++i] = otherValue;
但每次都会看到在for循环中有前缀增量的语句, :
but every once in a while I see statements with prefix increment in for-loops or just by their own:
for( int i = 0; i < count; ++i ) {
//do stuff
}
或
for( int i = 0; i < count; ) {
//do some stuff;
if( condition ) {
++i;
} else {
i += 4;
}
}
在后两种情况下 ++ i
看起来像是一个尝试产生smarty看起来的代码。我在监督什么?在后两种情况下,是否有理由使用 ++ i
而不是 i ++
?
In the latter two cases the ++i
looks like an attempt to produce smarty-looking code. Am I overseeing something? Is there a reason to use ++i
instead of i++
in the latter two cases?
推荐答案
如果我们忽略习惯的力量,'++ i'是一个更简单的操作在概念上:它只是添加一个值,然后使用它。
If we ignore force of habit, '++i' is a simpler operation conceptually: It simply adds one to the value of i, and then uses it.
i ++
另一方面,是 i
,将其存储为临时文件,向 i
添加一个,然后返回临时文件。即使在 i
更新后,我们仍需要保持旧价值。
i++
on the other hand, is "take the original value of i
, store it as a temporary, add one to i
, and then return the temporary". It requires us to keep the old value around even after i
has been updated.
正如Konrad Rudolph所说,使用 i ++
和用户定义的类型可能会有性能成本。
And as Konrad Rudolph showed, there can be performance costs to using i++
with user-defined types.
所以问题是,为什么不总是只是默认为 ++ i
?
So the question is, why not always just default to ++i
?
如果你没有理由使用`i ++',为什么呢?为什么你会默认更复杂的操作,而且可能执行起来更慢?
If you have no reason to use `i++´, why do it? Why would you default to the operation which is more complicated to reason about, and may be slower to execute?
这篇关于为什么在语句中的其他地方不使用值的情况下使用++ i而不是i ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!