C++ Decrement

C++ Decrement operation can be done using Arithmetic Decrement Operator --.

Decrement operator takes only one operand and decrements its value by one. Based on the side of operator at which the operand is given, there are two forms for Decrement Operator. They are:

  • Prefix
  • Postfix

In terms of execution, the main difference between prefix and postfix decrements is that: Prefix decrements the variable value and then participates in the expression evaluation or statement execution. But postfix first lets the expression evaluation or statement execution complete and then decrements the value of the operand.

C++ Prefix Decrement

For Prefix Decrement, the operand comes to the right of the operator --. Following is an example for prefix decrement.

--operand

Example

In the following example, we take an integer and decrement it using prefix form.

C++ Program

#include <iostream>  
using namespace std;

int main() {
   int a = 12;
   --a;
   cout << a << endl;
}

Output

11

C++ Postfix Decrement

For Postfix Decrement, the operand comes to the left of the decrement operator --.

operand--

Example

In the following example, we take an integer and decrement it using postfix form.

C++ Program

#include <iostream>  
using namespace std;

int main() {
   int a = 12;
   a--;
   cout << a << endl;
}

Output

11

C++ Postfix vs Prefix Decrement

Let us check the difference of postfix and prefix using an example program.

Example

In the following example, we shall perform postfix and prefix decrement on different variables, and then look into how they act during execution.

C++ Program

#include <iostream>  
using namespace std;

int main() {
   //postfix
   int a = 12;
   cout << a-- << endl; //12
   cout << a << endl << endl; //11

   //prefix
   int b = 12;
   cout << --b << endl; //11
   cout << b << endl; //11
}

Output

12
11

11
11

cout << a-- << endl;  takes the value of current a which is 12, executes the cout statement, and then decrements a. So, for the next statement, cout << a << endl << endl;, value of a is 11.

cout << --b << endl;  decrements the value of b to 11, executes the cout statement. So, when this statement is executed, b is printed as 11.

Decrement Float Value

Decrement operator can take a float variable as operand and decreases the values of the variable by 1.

Example

In the following example, we shall initialize a float variable with some value and decrement its value by 1 using -- operator.

C++ Program

#include <iostream>  
using namespace std;

int main() {
   float a = 12.5;
   a--;
   cout << a << endl;
}

Output

11.5

Conclusion

In this C++ Tutorial, we learned what decrement operator does, how to use decrement operator in prefix or postfix form, with the help of example C++ programs.