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