C++ Increment/Decrement 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--;
Whether the increment or decrement operator, it can be placed before (prefix) or after (postfix) the operand. For example:
x = x+1;
Can be written as:
++x; // 前缀形式
or:
x++; // 后缀形式
There is a slight difference between the prefix and postfix forms. If you use the prefix form, the increment or decrement is performed before the expression is evaluated; if you use the postfix form, it is performed after the expression is evaluated.
Example
Please see the example below to understand the difference between the two:
Example
#include
<
iostream
using
namespace
std;
int
main
(
)
{
int
a
=
21
;
int
c
;
// a is not incremented before the assignment
c
=
a
++;
cout
<<
"
Line 1 - Value of a++ is :
"
<<
c
<<
endl
;
// After the expression is evaluated, a is increased by 1
cout
<<
"
Line 2 - Value of a is :
"
<<
a
<<
endl
;
// a is incremented before the assignment
c
= ++
a
;
cout
<<
"
Line 3 - Value of ++a is :
"
<<
c
<<
endl
;
return
0
;
}
When the code above is compiled and executed, it produces the following result:
Line 1 - Value of a++ is :21
Line 2 - Value of a is :22
Line 3 - Value of ++a is :23
C++ Operators