Cpp - Increment and Decrement Operators

Introduction

The most common value to add or subtract from a variable is 1.

Increasing a variable by 1 is called incrementing, and decreasing it by 1 is called decrementing.

C++ includes a ++ increment operator and -- decrement operator to accomplish these tasks:

score++; 
my_int--; 

These statements increase score by 1 and decrease my_int by 1, respectively. They are equivalent to these more verbose statements:

score = score + 1; 
my_int = my_int - 1; 

Prefix and Postfix Operators

The increment operator ++ and decrement operator -- can be used either before or after a variable's name to achieve different results.

An operator placed before a variable's name is called a prefix operator, as in this statement:

++count; 

An operator placed after the variable name is called the postfix operator: count++;

The prefix operator occurs before the variable's value is used in the expression. The postfix is evaluated after.

int x = 5; 
int sum = ++x; 

After these statements are executed, the x variable and sum variable both equal 6.

The prefix operator in ++x causes x to be incremented from 5 to 6 before it is assigned to sum.

Compare it to this example:

int x = 5; 
int sum = x++; 

This causes sum to equal 5 and x to equal 6. The postfix operator causes x to be assigned to sum before it is incremented from 5 to 6.

Demo

#include <iostream> 
 
int main() /*from   www. j  a v a  2 s  .  c om*/
{ 
    int year = 2018; 
    std::cout << "The year " << ++year << " passes.\n"; 
    std::cout << "The year " << ++year << " passes.\n"; 
    std::cout << "The year " << ++year << " passes.\n"; 
 
    std::cout << "\nIt is now " << year << "."; 
    std::cout << " Have the Chicago Cubs won the World Series yet?\n"; 
 
    std::cout << "\nThe year " << year++ << " passes.\n"; 
    std::cout << "The year " << year++ << " passes.\n"; 
    std::cout << "The year " << year++ << " passes.\n"; 
 
    std::cout << "\nSurely the Cubs have won the Series by now.\n"; 
    return 0; 
}

Result