Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when we use k=k-- in c++?

Tags:

c++

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--?

like image 692
Boooooooooms Avatar asked Dec 11 '22 04:12

Boooooooooms


1 Answers

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

like image 190
Jans Avatar answered Jan 02 '23 06:01

Jans