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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With