I know that k--
equals to k = k - 1
. And I am wondering that what happens to k = k--
which I think may cause infinite loop. But in fact, I compile this code in Visual Studio 2017 and the output of k = k--
is the same as k = k - 1
.
So what's the implication of k = k--
?
Before c++17 the behavior was undefined, after that, It's fine according to [expr.ass]/1:
[...] the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand
and sequenced before means according to [intro.execution]/8
[...] An expression X is said to be sequenced before an expression Y if every value computation and every side effect associated with the expression X is sequenced before every value computation and every side effect associated with the expression Y.
In conclusion, k=k-1
and k=k--
are guaranteed to yield the same result.
also see: cppreference
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