C++ Increment Operator (++) - Postfix & Prefix

- March 13, 2018
This operator is used to add one value in the variable. It is a unary operator that is denoted by double plus sign (++).
Cpp increment operator sign

The double plus sign can be used before or after the (only single) variable name. In both cases, the value of the variable incremented by 1 but their functions are different in expressions and other operations. There are two types of increment operator:
  1. Postfix Increment Operator
  2. Prefix Increment Operator

What is Postfix Increment Operator?

When increment operator (++) is written after the variable name, it is known as postfix increment operator. In this case, first the value of variable is used in operation and then variable is incremented by one.
For example, to add 1 to variable "x", the statement is:
x++;

Example Program of Postfix Increment Operator

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

Output of Program

Value of a = 16 , Value of b = 15

Working of Postfix Increment Operator

The above statements are executed by the following rules:
  • First assignment statement a = 15; is executed and value 15 is assigned to variable "a".
  • Then statement b = a++; is executed by the following two steps:
    1. Value of "a" is assigned to "b". (Such as 15 assigned to variable b.
    2. 1 is added to "a" (Such as value of "a" becomes 16).
  • The value of "a" is printed as 16 and value of "b" printed as 15.
Note: The statement b = a++; is equivalent to following two statement:
b = a;
or
a = a + 1;

What is Prefix Increment Operator?

If the increment operator (++) is written before the variable name then it's know as prefix increment operator. In this case, first the variable incremented by one and then value of the variable is used in the operation. Such as, to add 1 to variable "y", the statement is:
++y;

Example Program of Prefix Increment Operator

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

Output of Program

Value of y = 21 , Value of z = 21

Working of Prefix Increment 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 incremented by 1 (Such as, it becomes 21)
    2. Then value of "y" is assigned to variable "z" (as value of "y" became 21, the value of z is also 21).
  • At last, the value of variables "y" and "z" is printed as 21.