C++ Increment and Decrement Operators


Postfix Operators

Post-increment operator: A post-increment operator is used to increment the value of a variable after executing the expression in which the operator is used. With the post-increment operator, the value of the variable is first used in an expression and then incremented.

Syntax:

int x = 10;
int a;
        
a = x++;

The value of a will be 10 because the value of x is assigned to a and then x is incremented.

Post-decrement operator: A post-decrement operator is used to decrement the value of a variable after executing the expression in which the operator is used. With the post-decrement operator, the value of the variable is first used in an expression and then decremented.

Syntax:

int x = 10;
int a;
        
a = x--;

The value of a will be 10 because the value of x is assigned to a and then x is decremented.

Prefix Operators

Pre-increment operator: A pre-increment operator is used to increment the value of a variable before using it in a expression. With the pre-increment operator, the value of the variable is first incremented and then used in an expression.

Syntax:

int x = 10;
int a;
    
a = ++x;

The value of a will be 11 because the value of x is incremented before it is assigned to a.

Pre-decrement operator: A pre-decrement operator is used to decrement the value of a variable before using it in a expression. With the pre-decrement operator, the value of the variable is first decremented and then used in an expression.

Syntax:

int x = 10;
int a;
        
a = --x;

The value of a will be 9 because the value of x is decremented before it is assigned to a.

Other Differences

The postfix operators have a higher precedence than the prefix operators, as well as a different associativity. The postfix operators are evaluated left-to-right while the prefix operators are evaluated right-to-left.

Program Example

#include <iostream>

using std::cout;
using std::endl;

int main()
{
    int x = 7;
    
    cout << "Value of x is " << x << endl;
    
    cout << "Value of x is now" << x++ << endl;

    cout << "Value of x is now " << x << endl;

    cout << "Value of x is now " << ++x << endl;

    cout << "Value of x is now " << x << endl;

    return 0;
}

Output produced by the program:

Value of x is 7
Value of x is now 7
Value of x is now 8
Value of x is now 9
Value of x is now 9