在C语言中,使用++i和i++之间的区别是什么,在for循环的增量块中应该使用哪个?


当前回答

++i增加值,然后返回该值。

i++返回值,然后使其递增。

这是一个微妙的区别。

对于For循环,使用++i,因为它稍微快一些。i++将创建一个被丢弃的额外副本。

其他回答

++i可以比i++稍微快一点的原因是,i++可以在i的值被递增之前要求它的本地副本,而++i从不这样做。在某些情况下,一些编译器会尽可能地优化它……但这并不总是可能的,并不是所有编译器都这样做。

我尽量不太依赖编译器优化,所以我会遵循Ryan Fox的建议:当我可以使用两者时,我会使用++ I。

主要的区别是 i++ Post(After Increment)和 ++i Pre(增量前) Post if I =1,循环增量为1,2,3,4,n 如果I =1,循环会增加2 3 4 5 n

我假设你现在已经理解了语义上的差异(尽管说实话我想知道为什么 人们会问“运算符X是什么意思”的问题,而不是阅读, 你知道的,一本书或网络教程之类的。

不管怎样,至于用哪个,忽略性能的问题 即使在c++中也不太重要。这是你做决定时应该遵循的原则 使用哪一种:

用代码表达你的意思。

如果语句中不需要value-before-increment,就不要使用这种形式的操作符。这是一个小问题,但除非你的风格指南禁止这样做 版本完全赞成其他的(又名愚蠢的风格指南),你应该使用 最准确地表达你要做的事情的形式。

QED,使用预增量版本:

for (int i = 0; i != X; ++i) ...

i++和++ I

这段小代码可能有助于从不同的角度来看待与已经发布的答案的差异:

int i = 10, j = 10;
  
printf ("i is %i \n", i);
printf ("i++ is %i \n", i++);
printf ("i is %i \n\n", i);
  
printf ("j is %i \n", j);
printf ("++j is %i \n", ++j);
printf ("j is %i \n", j);

结果是:

//Remember that the values are i = 10, and j = 10

i is 10 
i++ is 10     //Assigns (print out), then increments
i is 11 

j is 10 
++j is 11    //Increments, then assigns (print out)
j is 11 

注意之前和之后的情况。

for循环

至于在for循环的增量块中应该使用它们中的哪一个,我认为我们能做的最好的决定是使用一个很好的例子:

int i, j;

for (i = 0; i <= 3; i++)
    printf (" > iteration #%i", i);

printf ("\n");

for (j = 0; j <= 3; ++j)
    printf (" > iteration #%i", j);

结果是:

> iteration #0 > iteration #1 > iteration #2 > iteration #3
> iteration #0 > iteration #1 > iteration #2 > iteration #3 

我不知道你怎么想,但我没有看到它的用法有任何不同,至少在for循环中是这样。

在循环中使用两者的有效结果是相同的。换句话说,循环将在两个实例中做完全相同的事情。

就效率而言,选择i++而不是++i可能会有一定的损失。根据语言规范,使用后增量操作符应该创建操作符所作用的值的额外副本。这可能是额外操作的来源。

但是,您应该考虑上述逻辑的两个主要问题。

Modern compilers are great. All good compilers are smart enough to realize that it is seeing an integer increment in a for-loop, and it will optimize both methods to the same efficient code. If using post-increment over pre-increment actually causes your program to have a slower running time, then you are using a terrible compiler. In terms of operational time-complexity, the two methods (even if a copy is actually being performed) are equivalent. The number of instructions being performed inside of the loop should dominate the number of operations in the increment operation significantly. Therefore, in any loop of significant size, the penalty of the increment method will be massively overshadowed by the execution of the loop body. In other words, you are much better off worrying about optimizing the code in the loop rather than the increment.

在我看来,整个问题可以归结为一种风格偏好。如果您认为预增量更具可读性,那么就使用它。就我个人而言,我更喜欢后增量,但这可能是因为这是我在了解优化之前学到的东西。

这是一个典型的过早优化的例子,像这样的问题有可能分散我们对设计中严肃问题的注意力。然而,这仍然是一个很好的问题,因为在“最佳实践”中没有统一的用法或共识。