Christian Bau wrote:
In article <d0**************************@posting.google.com >,
cc****@hotmail.com (ccwork) wrote:
p = p->next = q;
Why it is undefined?
operator "=" is right-associative i.e. "p = p->next = q;" is
equivalent to "p = (p->next = q);
And I think another interpretation of sequence point is: between 2
sequence point a variable cannot be modified twice. In "p = p->next
= q;", "p->next" is modified once, "p" is modified once. (Let say we
use another pointer "k" such that "k=p->next" and then "p = p->next =
q;" become "p = k = q". Obviously the "k" and "p" are modified once
individually.)
There are no rules in C in which order operands are evaluated.
The value of q will eventually be stored into p. Will the p in
"p->next" be read before or after q is stored into p?
Before. In some cases there are implicit rules about the relative
order of evaluation of expressions. Let's take the trivial example of:
p = p + 1;
According to your logic, this would be undefined. However, 6.5.2 gets
us off the hook:
6.5 Expressions
..
.. 2 Between the previous and next sequence point an object
.. shall have its stored value modified at most once by the
.. evaluation of an expression. Furthermore, the prior value
.. shall be accessed only to determine the value to be stored.
The expression 'p + 1' represents 'the value to be stored'. Within 'p
+ 1', p represents 'the prior value'. Here, p is 'accessed only to
determine the value to be stored'.
Simply mentioning 'the prior value' creates an implicit, partial
operand evaluation order. p must not be modified until its 'prior
value' is evaluated.
The expression:
p = p->next = q;
Is evaluated much the same as the above, and is defined behavior.
'p->next = q' is the 'value to be stored'. Since p is being modified
in the expression, the p in p->next is the 'prior value'. Since
p->next is a participant in the expression 'p->next = q' (the 'value to
be stored'), it's clear that 'the prior value [is] accessed only to
determine the value to be stored'.
It *is* defined behavior. Whether or not it is good style is another
matter altogether.
Mark F. Haigh
mf*****@sbcglobal.net