My question are;
1.What does it mean by, if an object is written to within a full expression, any and all accesses to it within the same expression must
be directly involved in the computation of the value to be written.?
With a sub-expression like i++
, i
is written to. Moreover, assignment is an expression, so in i = 2
, i
is written to. It may not be immediately obvious that a = b
is an expression, but it is. This is why you can do things like a = b = c
, which is good, and if (a = b)
which is less good.
So what it is saying is that if you write to i
, with =
, or pre- or post- increment, then any access to i must be as part of the calculation of the new value of i. However, and this is important, the only thing involved in the calculation of pre and post increment is the value of i
at the start of the statement.
2.what does it mean by, The example a[i] = i++ is disallowed because one of the accesses
of i (the one in a[i]) has nothing to do with the value which ends up
being stored in i (which happens over in i++)
Precisely what it says. When you access i
in a[i]
it is not part of the calculation of the new value of i
that results from i++
.
Could someone explain it in some easy way?
Easy way: Don't use pre or post increment in an expression. always use them in statements by themselves. If you really really must, do NOT use the same variable anywhere else in the entire statement.
It is undefined behavior because the evaulation of *p
is unsequenced in related to the evaluation of *p--
. There is no sequence point. For all assignment operators, 6.5.16:
The side effect of updating the stored value of the left operand is
sequenced after the value computations of the left and right operands.
The evaluations of the operands are unsequenced.
6.5 states that it is UB:
If a side effect on a scalar object is unsequenced relative to either
a different side effect on the same scalar object or a value
computation using the value of the same scalar object, the behavior is
undefined. If there are multiple allowable orderings of the
subexpressions of an expression, the behavior is undefined if such an
unsequenced side effect occurs in any of the orderings.
Best Answer
This expression is OK because the comma operator is a sequence point:
However do not confuse it with the following where the comma is not acting as a sequence point:
The multiplication operator is not a sequence point.
(Excuse me hijacking your answer)
From ยง3.4 of ISO 9899:1999 (C Standard):