c ++增量运算符

时间:2010-10-15 03:44:48

标签: c++ increment

  

可能重复:
  Difference between i++ and ++i in a loop?

i ++ ++ i 之间有区别吗?

4 个答案:

答案 0 :(得分:3)

i ++是postincrement,++ i是preincrement。前者允许您在表达式中使用i的值,然后在结尾处递增i。后来我先增加,然后允许你使用它。例如:

int value_of_i_before_increment=i++;

int value_of_i_after_increment=++i;

答案 1 :(得分:2)

i ++在语句后递增i。 ++ i在评估语句之前递增i。

答案 2 :(得分:2)

i ++是后增量。它返回i的副本,然后递增i的值。

++我是预增量。它递增i,THEN返回i的值。

答案 3 :(得分:1)

++c是预先递增的,因此在使用之前递增该值,并且c++是后递增的,因此您使用该值然后递增它。

int c;
c = 5;
cout << c++; // prints 5, then sets the value to 6
c = 5;
cout << ++c // sets the value to 6, then prints 6

所以这可能会对循环等产生影响,即

int i;
for (i=0; i < 2; i++) cout << i; // prints 0, then 1
for (i=0; i < 2; ++i) cout << i; // prints 1, then 2

还有潜在的性能影响。有关详细信息,请参阅this post

相关问题