C++ Decrement Operator (--) | Postfix and Prefix

- March 17, 2018
This operator is used to subtract 1 from the value of the variable. It is a unary operator that is denoted by double minus sign (--). It can be applied to a single variable only. The double minus sign can be used before or after the variable name. In both cases, the value of the variable decremented by 1 but their functions are different in expressions and other operations. There are two types of decrement operator:
  • Postfix Decrement Operator
  • Prefix Decrement Operator

What is Postfix Decrement Operator?

When decrement operator (--) is written after the variable name, it is known as postfix decrement operator. In this case, first the value of variable is used in operation and then variable is decremented by one. For example, to subtract 1 from the variable "i", the statement is:
i--;
How to use decrement operator in cpp

Example Program of Postfix Decrement Operator

To clear the concept about it, a set of statements is as follows:
#include<iostream>
using namespace std;
main()
  {
    int i = 40, b;
    b = i--;
    cout<<"Value of i ="<<i<< "<<Value of b ="<<b;
return 0;
}

Output of Program

Value of i = 39 , Value of b = 40

Working of Postfix Increment Operator

The above statements are executed by the following rules:
  • First assignment statement i = 40; is executed and value 40 is assigned to variable "i".
  • Then statement b = i--; is executed in in the following two steps:
    1. In first step, value of "i" is assigned to "b". (Such as 40 assigned to variable b.)
    2. In second step, 1 is subtracted from "i" (Such as value of "i" becomes 39).
  • The value of "i" is printed as 39 and value of "b" printed as 40.

Note: The statement b = i--; is equivalent to following two statements:
c = a;
a = a - 1;

What is Prefix Decrement Operator?

If the decrement operator (--) is written before the variable name then it's known as prefix decrement operator. In this case, first the variable decremented by one and then value of the variable is used in the operation. Such as, to subtract 1 from variable "m", the statement is:
--m;

Example Program of Prefix Decrement Operator

To understand it batter, look at the following example program:
#include<iostream>
using namespace std;
main()
 {
   int y = 20, z;
    z = --y;
    cout<<"Value of y ="<<y<< "<<Value of z ="<<z;
return 0;
}

Output of Program

Value of y = 19 , Value of z = 19

Working of Prefix Decrement Operator

The above program is executed by the following rules:
  • First assignment statement y = 20; is executed and value 20 is assigned to variable "y".
  • Then statement z = --y; is executed by the following two steps:
    1. First value of "y" is decremented by 1 (Such as, it becomes 19)
    2. Then value of "y" is assigned to variable "z" (as value of "y" became 19, the value of z is also 19).
  • At last, the value of variables "y" and "z" is printed as 19.