Incrementing and decrementing variables
Incrementing [adding 1 to] and decrementing [subtracting 1 from] a variable are both so common that they have their own operators.
Prefix increment [pre-increment] | ++ | ++x | Increment x, then return x |
Prefix decrement [pre-decrement] | –– | ––x | Decrement x, then return x |
Postfix increment [post-increment] | ++ | x++ | Copy x, then increment x, then return the copy |
Postfix decrement [post-decrement] | –– | x–– | Copy x, then decrement x, then return the copy |
Note that there are two versions of each operator -- a prefix version [where the operator comes before the operand] and a postfix version [where the operator comes after the operand].
The prefix increment/decrement operators are very straightforward. First, the operand is incremented or decremented, and then expression evaluates to the value of the operand. For example:
#include
int main[]
{
int x { 5 };
int y = ++x; // x is incremented to 6, x is evaluated to the value 6, and 6 is assigned to y
std::cout