在C语言中,使用++i和i++之间的区别是什么,在for循环的增量块中应该使用哪个?
当前回答
简单地说,两者之间的区别在于步骤,请看下图。
例子:
int i = 1;
int j = i++;
j的结果是1
int i = 1;
int j = ++i;
j的结果是2
注意:在这两种情况下i的值都是2
其他回答
++i(前缀操作):递增,然后赋值 (例如):int I = 5, int b = ++ I 在这种情况下,先将6赋值给b,然后递增到7,依此类推。
i++(后缀操作):赋值,然后递增 (例如):int I = 5, int b = i++ 在这种情况下,5首先被赋值给b,然后增加到6,依此类推。
在for循环的情况下:i++主要用于,因为通常我们在for循环中递增之前使用i的起始值。但是根据您的程序逻辑,它可能会有所不同。
请不要担心哪个“效率”(真的是速度)更快。现在我们有编译器来处理这些事情。使用任何一个有意义的,在此基础上更清楚地表明你的意图。
A =i++表示A包含当前i的值。
A =++i表示A包含i的增量值。
唯一的区别是变量的增量和运算符返回值之间的操作顺序不同。
这段代码及其输出解释了区别:
#include<stdio.h>
int main(int argc, char* argv[])
{
unsigned int i=0, a;
printf("i initial value: %d; ", i);
a = i++;
printf("value returned by i++: %d, i after: %d\n", a, i);
i=0;
printf("i initial value: %d; ", i);
a = ++i;
printf(" value returned by ++i: %d, i after: %d\n",a, i);
}
输出结果为:
i initial value: 0; value returned by i++: 0, i after: 1
i initial value: 0; value returned by ++i: 1, i after: 1
所以基本上++i返回的值是在它被加1之后,而i++返回的值是在它被加1之前。最后,在这两种情况下,i的值都会增加。
另一个例子:
#include<stdio.h>
int main ()
int i=0;
int a = i++*2;
printf("i=0, i++*2=%d\n", a);
i=0;
a = ++i * 2;
printf("i=0, ++i*2=%d\n", a);
i=0;
a = (++i) * 2;
printf("i=0, (++i)*2=%d\n", a);
i=0;
a = (i++) * 2;
printf("i=0, (i++)*2=%d\n", a);
return 0;
}
输出:
i=0, i++*2=0
i=0, ++i*2=2
i=0, (++i)*2=2
i=0, (i++)*2=0
很多时候是没有区别的
当返回值被赋给另一个变量时,或者当增量与应用操作优先级的其他操作一起执行时,差异很明显(i++*2不同于++i*2,以及(i++)*2和(++i)*2),在许多情况下它们是可互换的。一个经典的例子是for循环语法:
for(int i=0; i<10; i++)
有同样的效果吗
for(int i=0; i<10; ++i)
效率
预增量总是至少和后增量一样高效:事实上,后增量通常包括保留前一个值的副本,并可能添加一些额外的代码。
正如其他人所建议的,由于编译器优化很多次,它们同样有效,可能在这些情况下存在for循环。
要记住的规则
为了不混淆这两个运算符,我采用了下面的规则:
将运算符++相对于变量i的位置与++操作相对于赋值的顺序相关联
换言之:
++ before I表示必须在赋值之前进行递增; I之后的++表示必须在赋值之后进行递增:
在循环中使用两者的有效结果是相同的。换句话说,循环将在两个实例中做完全相同的事情。
就效率而言,选择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.
在我看来,整个问题可以归结为一种风格偏好。如果您认为预增量更具可读性,那么就使用它。就我个人而言,我更喜欢后增量,但这可能是因为这是我在了解优化之前学到的东西。
这是一个典型的过早优化的例子,像这样的问题有可能分散我们对设计中严肃问题的注意力。然而,这仍然是一个很好的问题,因为在“最佳实践”中没有统一的用法或共识。