C++ 自增和自减运算符



自增运算符 ++ 将 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

当自增或自减用作表达式的一部分时,前缀和后缀形式之间存在重要区别。如果使用前缀形式,则会在表达式其余部分之前进行自增或自减;如果使用后缀形式,则会在计算完整个表达式后进行自增或自减。

示例

以下示例说明了这种区别:

#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
cpp_operators.htm
广告