Priority of increment and decrement pointers 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 a decrement operand). Can anyone enlighten me about this?

Thanks!

+7
source share
3 answers

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

In any case, you cannot double-change the same object between points in a sequence, so your “working” example invokes undefind behavior. The output can be anything that the compiler does. If you just ask out of curiosity that it is good, but if it has to do with your actual code, you may do something wrong.

+12
source

predecrement --a decreases a , and then returns a . Thus, you can continue to modify it in any way, including post-declassification.

postdecrement a-- decrements a , but returns the value before decrement. This gives you a copy of a . But you cannot pre-create this copy. This is not an lvalue, so nothing will decrease there. That is why this is a mistake.

Think of predefinition as returning a reference to a , and postdecrement when returning at a constant value.

+8
source
 (--a)-- 

This behavior is undefined because you are modifying the same object twice without an intermediate point in the sequence. The compiler should not report when you call UB - it cannot even detect UB in many situations. But if you turn on the correct warnings (and you should look at what yours provides), perhaps it will be possible.

 --(a--) 

Incrementing a prefix requires an lvalue value, but a postfix decrement returns an r value. This is a bug that, unlike undefined behavior, the compiler should report.

+4
source

All Articles