Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 738
zw324 Avatar asked May 20 '11 03:05

zw324


2 Answers

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.

like image 115
Chris Lutz Avatar answered Nov 05 '22 09:11

Chris Lutz


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.

like image 37
Tim Avatar answered Nov 05 '22 10:11

Tim