C++ Increment and Decrement Operators

C++ Operators

The increment operator ++ adds 1 to the operand, and the decrement operator -- subtracts 1 from the operand. Therefore:

x = x+1;
 
等同于
 
x++;

Similarly:

x = x-1;
 
等同于
 
x--;

Both the increment and decrement operators can be placed before (prefix) or after (suffix) the operand. For example:

x = x+1;
 
可以写成:
 
++x; // 前缀形式

Or:

x++; // 后缀形式

There is a slight difference between the prefix and suffix forms. If the prefix form is used, the increment or decrement is completed before the expression is evaluated; if the suffix form is used, the increment or decrement is completed after the expression is evaluated.

Example

Please look at the following example to understand the difference between the two:

Example

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

When the above code is compiled and executed, it produces the following results:

Line 1 - Value of a++ is :21
Line 2 - Value of a is :22
Line 3 - Value of ++a is  :23

C++ Operators

other extensions