Related Tags

operators
c++
communitycreator

# How to use of increment and decrement operators in C++

Onyejiaku Theophilus Chidalu

### 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 $1$ to its operand, and the decrement operator -- subtracts $1$ 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 operation

cout << "x = " << x << ", y = " << y << endl;

cout << "After post-increment of '1' on 'x' and post-decrement of '1' on 'y'" << endl;
x++; // Post-increment operation
y--; // Post-decrement operation

cout << "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 $1$ 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 $1$.

Similarly, the expression statements --y and y-- are both equivalent to the assignment y = y + 1. They simply decrease the value of y by $1$.

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.

RELATED TAGS

operators
c++
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time