C ++ 增量和减量运算符
增量运算符 ++ 将其操作数加1,减量运算符 — 将其操作数减1。因此 −
x = x+1;is the same asx++;
同样地 −
x = x-1;is the same asx--;
递增和递减操作符可以位于操作数前面(前缀形式)或后面(后缀形式)。例如:
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 :21Line 2 - Value of a is :22Line 3 - Value of ++a is :23
