Search code examples
c++incrementdecrement

Precedence of increment and decrement opreators in C++


I tried this on my gcc:

int a=1;
cout<<(--a)--;

and the output is 0; but change it to

cout<<--(a--);

results in an error (lvalue required as decrement operand). Could someone enlighten me about this?

Thanks!


Solution

  • Both versions of ++ require lvalues as arguments, but the prefix version returns an lvalue as an argument, while the postfix version returns an rvalue.

    Either way, you can't modify the same object twice between sequence points, so your "working" example invokes undefind behavior. The output can be whatever the compiler feels like doing. If you're just asking out of curiosity that's fine, but if this is relevant to your actual code you might be doing something wrong.