++i 和 i++ 有什么区别? [英] What is the difference between ++i and i++?
问题描述
在C中,使用++i
和i++
有什么区别,哪个应该用在for
循环?
In C, what is the difference between using ++i
and i++
, and which should be used in the incrementation block of a for
loop?
推荐答案
++i
将增加i
的值,然后返回增加的值.++i
will increment the value ofi
, and then return the incremented value.i = 1; j = ++i; (i is 2, j is 2)
i++
将增加i
的值,但返回i
增加前的原始值.i++
will increment the value ofi
, but return the original value thati
held before being incremented.i = 1; j = i++; (i is 2, j is 1)
对于
for
循环,两者都可以.++i
似乎更常见,也许是因为 K&R.For a
for
loop, either works.++i
seems more common, perhaps because that is what is used in K&R.在任何情况下,遵循首选
++i
而不是i++
"的准则,你就不会出错.In any case, follow the guideline "prefer
++i
overi++
" and you won't go wrong.有一些关于
++i
和i++
的效率的评论.在任何非学生项目编译器中,不会有性能差异.您可以通过查看生成的代码来验证这一点,它们将是相同的.There's a couple of comments regarding the efficiency of
++i
andi++
. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.效率问题很有趣……这是我试图回答的问题:C 中的 i++ 和 ++i 之间有性能差异吗?
The efficiency question is interesting... here's my attempt at an answer: Is there a performance difference between i++ and ++i in C?
正如 @OnFreund 所指出的,C++ 对象是不同的,因为
operator++()
是一个函数,编译器不知道优化创建一个临时对象来保存中间值.As @OnFreund notes, it's different for a C++ object, since
operator++()
is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value.这篇关于++i 和 i++ 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!