pre-increment and post-increment in C++

Maybe you have wondered why there are 2 types if increment operators in C++ and why it matters in some situations.

Lets have a variable i of type int. Pre-increment would be ++i, and post-increment is i++ as we learned it in school;

The result in both ways is the same, it increments the variable i by 1. The difference is how it behaves when passing i along to a function:

void doSomething(int i) {
  std::cout << i << std::endl;
}

int i = 12;
doSomething(i++); // prints 12
// i is now 13
int i = 12;
doSomething(++i); // prints 13
// i is now 13

The explanation

Pre-increment increments the value of i and returns a reference to the now increased i.

Post-increment makes a copy of i, then increments i, but returns the copy.

Leave a Reply