2

I am trying to concatenate post and pre-increment operators. I see that for some combinations involving post operators, I get the unassignable error. Is it because the post operator will be evaluated once the j's value is defined. can anyone give me a deeper understanding of this?

I am trying these weird scenarios as I am trying to get better in c++. If there is any way to learn better. It would be really appreciated.

#include <iostream>
int main() {
    int j = 0;
    int i = 0;
    // This works
    j = (++i)++;
    std::cout << "J is: " << j << "\n";

    // This doesn't
    j = ++(i++);
    std::cout << "J is: " << j << "\n";

    // This does
    j = (i++);
    std::cout << "J is: " << j << "\n";

    // This doesn't
    j = (i++)++;
    std::cout << "J is: " << j << "\n";
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Yash Kapoor
  • 93
  • 2
  • 12

1 Answers1

3

The difference is that the prefix operator ++ returns an lvalue while the postfix operator ++ returns an rvalue.

So for example you may write (many pluses of an even number)

j = ++++++++i;

but you may write only (only two pluses)

j = i++;

From the C++17 Standard ((postfix) 8.5.1.6 Increment and decrement)

1 The value of a postfix ++ expression is the value of its operand....

And ((prefix) 8.5.2.2 Increment and decrement)

1 ... The result is the updated operand; it is an lvalue...

Relative to your question consider one more interesting difference between post-increment and pre-increment. Here is a demonstrative program

#include <iostream>

int main() 
{
    int a[] = { 10, 20 };

    int *p = a;

    std::cout << p++[0] << '\n';

    p = a;

    std::cout << ++++p[0] << '\n';

    return 0;
}

Its output is

10
12

The difference is that the subscript operator is defined through using the postfix expression.

So this expression p++[0] is equivalent to ( p++ )[0]

While this expression ++++p[0] is equivalent to ++++( p[0] )

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335