Hakkı Bluoyd
Hakkı Bluoyd

Reputation: 11

Post-Increment of an Post-Increment in C++

If I use a nested increment operator in C++, such as

int a = 1;
int b = (a++)++;

It gives a compile-time error:

error: lvalue required as increment operand

However, if I write

int a = 1;
int b = ++(++a);

The new value of b becomes 3.

What is the reason for this?

Upvotes: 1

Views: 321

Answers (2)

Ranoiaetep
Ranoiaetep

Reputation: 6667

The reason here is it doesn't make sense to perform a post-increment to the result that is produced by a post-increment.

Let's first see what exactly a++ does:

int operator++(int)
{
    auto temp = *this;
    *this += 1;
    return temp;
}

So when you perform a++, a would be incremented by 1, and then it returns a temporary value that is equals to what a used to be.

Now imagine if you perform this for a second time, what you are essentially doing is:

int post_increment_twice()
{
    auto temp1 = *this;
    *this += 1;
    auto temp2 = temp1;
    temp1 += 1;
    return temp2;
}

You would notice that the result is exactly the same as post increment once.

  • *this was incremented once
  • then you return the value *this used to be.

  • In fact, it doesn't make sense to perform a post-increment on any temporary values.

Post-increment performs an increment to the value inside the function. However, by passing in a temporary value, you lose the access the incremented object. And returns a value that is equal to the temporary value before it was incremented.


While it is possible to overload a post-increment operator for custom classes to accept temporary values. But with integers, it simply doesn't make sense to accept that, thus it was not allowed.

Upvotes: 1

3CxEZiVlQ
3CxEZiVlQ

Reputation: 39050

(a++) returns a temporary rvalue with an old value of a. There is no postincrement operator available to rvalues.

Upvotes: 6

Related Questions