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
廣告