The value of the expression x--
is the current value of x
, before the stored value is decremented. So, in calling foo(x--)
, the value of the argument to foo
is always the same as its current value, yielding infinite recursion.
Note, however, that the behavior of both programs is potentially undefined, and depends on the order of evaluation of the subexpressions of foo(x--) + x
and foo(--x) + x
. Let's consider the first program, which contains the expression
foo(--x) + x
If the subexpressions are evaluated in the following (valid!) order, the program has undefined behavior:
x
is read to compute the value of the x
as the right-hand side operand of +
,
x
is read to compute the value of the x
as an operand of --
,
x
is written to store the new value of x
after it is decremented
foo
is called
The only sequence point here is between steps 3 and 4: after the argument expression is evaluated, before the function is called. Because x
is read twice (in [1] and [2]) and written once (in [3]) and because one of the reads (in [1]) is not for the purpose of computing the new value to be stored, the behavior is undefined.
Evaluation order is unspecified, but if this evaluation order is the order that is used, the program has undefined behavior.
The same reasoning applies equally to the second program.
It would be best to use x - 1
as the argument to foo
, as this expression does not modify the value of x
.