Is the behaviour of this statement of assignment and decrementation well defined?

108 Views Asked by At

The following statement does not really make sense:

value = value--;

I accidentially wrote this instead of just value-- or value = value-1 . But since it worked on my machine as intended, the error was not noticed.

Now I want to know, if this statement is well defined and will have the same result on all machines. Or can this lead to different results?

2

There are 2 best solutions below

0
MSalters On BEST ANSWER

No, this is not well-defined, even in C++17. (Assuming built-in =, not a function call). The assignment to the left side is sequenced-after the calculation of the value on the right side. But the side effects of the right-hand side (value--) are not sequenced relative to the assignment. And decrementing value is a side effect of value--.

2
sn01 On

You are correct.The statement value = value--; does not make sense because it is attempting to decrement the value of value and assign the result back to value in a single statement. However, the behavior of the decrement operator -- is to first return the current value of the variable and then decrement it. So in this case, value-- would return the current value of value and then decrement it, but the assignment value = would then set value to the original value before the decrement. As a result, the statement value = value--; would have no effect on the value of value. It would essentially be equivalent to writing value = value;.