RK_15
RK_15

Reputation: 939

Pre and post increment behaviour in C++

(C++) Why
std::cout << ++(a++);
shows error: lvalue required as increment operand
but
std::cout << (++a)++;
shows output "1"

(Java) But in Java in both the cases it throws exception. Cause increment and decrement operators work on variable not on values. And output of parentheses operator is always value.

Thanks in advance.

Upvotes: 1

Views: 44

Answers (1)

passing_through
passing_through

Reputation: 1931

The return type of preincrement is T&, which allows you to modify it (because it's a non-const reference). Postincrement returns T: it's an unnamed value in the t++ context. Therefore, the result is considered const-like so you can't change its state.

If you want to find more information, you can search up lvalues, (p)rvalues etc. but they might be hard to understand.

Upvotes: 1

Related Questions