C++ Increment/Decrement Operators

Introduction

Increment/decrement operators increment/decrement the value of the object.

The operators are:

++x // pre-increment operator 
x++ // post-increment operator 
--x // pre-decrement operator 
x-- // post-decrement operator 

A simple example:

#include <iostream> 

int main() //from   w w  w .  j  av a2 s . c o m
{ 
    int x = 123; 
    x++;    // add 1 to the value of x 
    ++x;    // add 1 to the value of x 
    --x;    // decrement the value of x by 1 
    x--;    // decrement the value of x by 1 
    std::cout << "The value of x is: " << x; 
} 

Both pre-increment and post-increment operators add 1 to the value of our object.

Both pre-decrement and post-decrement operators subtract one from the value of our object.

The difference between the two is

  • With the pre-increment operator, a value of 1 is added first. Then the object is evaluated/accessed in expression.
  • With the post-increment, the object is evaluated/accessed first, and after that, the value of 1 is added.

To the next statement that follows, it does not make a difference.




PreviousNext

Related