How to use of increment and decrement operators in C++
Overview
Of the many features C++ inherited from C, some of the most useful are the increment operator ++ and decrement operator --.
These operators transform a variable into a statement expression that abbreviates a special form of assignment.
Increment and decrement operators
The increment operator ++ adds to its operand, and the decrement operator -- subtracts from its operand.
Code
Let’s write a code using the increment operator ++ and the decrement operator --.
#include <iostream>using namespace std;int main() {int x = 10, y = 11;cout << "Initial value of 'x' and 'y'" << endl;cout << "x = " << x << ", y = " << y << endl;cout << "After pre-increment of '1' on 'x' and pre-decrement of '1' on 'y'" << endl;++x; // Pre-increment operation--y; // Pre-decrement operationcout << "x = " << x << ", y = " << y << endl;cout << "After post-increment of '1' on 'x' and post-decrement of '1' on 'y'" << endl;x++; // Post-increment operationy--; // Post-decrement operationcout << "x = " << x << ", y = " << y << endl;return 0;}
Explanation
From the program above, both the pre-increment operator (++x) and the post-increment operator (x++) have the same effect here, i.e., they add to the value of x.
Similarly, both the pre-decrement operators (--y) and the post-decrement operator (y--) have the same effect here, i.e., they subtract 1 from the value of y.
When used as a stand-alone expression statement, ++x and x++ are both equivalents to the assignment x = x + 1. They simply increase the value of x by .
Similarly, the expression statements --y and y-- are both equivalent to the assignment y = y + 1. They simply decrease the value of y by .
It is interesting to note that the increment operator
++was used in the name C++ because it “increments” the original C programming language; it has everything that C has and more.