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!
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!
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.
predecrement --a
decrements a
, and then gives you back a
itself. So you can then go on to modify it any way you want, including a postdecrement.
postdecrement a--
decrements a
but gives you back a's value before the decrement. It's essentially giving you a copy of a
. But you cannot then predecrement this copy. It's not an lvalue, so there's nothing to decrement. That's why it's an error.
Think of predecrement as returning a reference to a
, and postdecrement as returning by constant value.
(--a)--
This is undefined behavior, as you modify the same object twice without an intervening sequence point. The compiler is not required to report when you invoke UB – it can't even detect UB in many situations. But if you turn on the right warnings (and you should look at what yours provides), it may be able to, sometimes.
--(a--)
Prefix decrement requires an lvalue, but postfix decrement returns an rvalue. This is an error that, unlike undefined behavior, the compiler is required to report.