目录

增量运算符(Increment operator)

增量运算符++将1添加到其操作数,减量运算符 - 从其操作数中减去1。 因此 -

x = x+1;
is the same as
x++;

同样 -

x = x-1;
is the same as
x--;

递增和递减运算符都可以在操作数之前(前缀)或后跟(后缀)。 例如 -

x = x+1;
can be written as
++x; // prefix form

或者 -

x++; // postfix form

当增量或减量用作表达式的一部分时,前缀和后缀形式之间存在重要差异。 如果使用前缀形式,则在表达式的其余部分之前将完成递增或递减,如果使用后缀形式,则在评估完整表达式之后将执行递增或递减。

例子 (Example)

以下是了解这种差异的例子 -

#include <iostream>
using namespace std;
main() {
   int a = 21;
   int c ;
   // Value of a will not be increased before assignment.
   c = a++;   
   cout << "Line 1 - Value of a++ is :" << c << endl ;
   // After expression value of a is increased
   cout << "Line 2 - Value of a is :" << a << endl ;
   // Value of a will be increased before assignment.
   c = ++a;  
   cout << "Line 3 - Value of ++a is  :" << c << endl ;
   return 0;
}

编译并执行上述代码时,会产生以下结果 -

Line 1 - Value of a++ is :21
Line 2 - Value of a is :22
Line 3 - Value of ++a is  :23
↑回到顶部↑
WIKI教程 @2018