可能重复:
Is there a performance difference between i++ and ++i in C++?
我看到了许多地方,他们使用这样的循环:
for(i = 0; i < size; ++i){ do_stuff(); }而不是(我-&大多数人-使用)
for(i = 0; i < size; i++){ do_stuff(); }++i应该给出与i++完全相同的结果(除非操作符重载差分)。我看到了它的正常循环和STL迭代循环。
为什么他们使用++i而不是i++呢?有任何编码规则推荐这样做吗?
编辑:关闭因为我发现它与Is there a performance difference between i++ and ++i in C++?完全重复
发布于 2011-09-25 16:54:45
简单地说:++x is pre-increment and x++ is post-increment that is in the first x is incremented before being used and in the second x is incremented after being used.
示例代码:
int main()
{
int x = 5;
printf("x=%d\n", ++x);
printf("x=%d\n", x++);
printf("x=%d\n", x);
}o/p:
x=6
x=6
x=7发布于 2011-09-25 16:52:55
这两者确实是相同的,因为第三部分是在循环的每一次迭代之后执行的,并且它的返回值不用于任何东西。这只是一个偏好的问题。
https://stackoverflow.com/questions/7546988
复制相似问题