NoNo for Associativity of Assignments?

Stewart Gordon smjg_1998 at yahoo.com
Mon Feb 26 15:49:49 PST 2007


Manfred Nowak Wrote:

> Now that the associativity of comparisons has been dropped, I have
> the heart to point the readers attention to the associativity of
> assignments: 
<snip>
> | It is an error to depend on order of evaluation when it is not
> | specified. 
> 
> This means: "a = b = c;" is an error unless "a == b" and "b == c"!
<snip>

Your reasoning appears to be flawed.

a, b and c have no evaluation to be performed.  The only evaluations are of (b = c) and of (a = result).  The evaluation order _is_ specified: the result of (b = c) must be evaluated before it can be assigned to a.

Even if the lvalues do need to be evaluated, you're still not necessarily relying on evaluation order.

For example, for this:

    a[++i] = b[j -= 42] = c;

the evaluation order could be any topological sort of this graph:

++i ----------------> &a[++i] ---------------\
                                             +--> a[++i] = b[j -= 42] = c
j -= 42 --> &b[j -= 42] --> b[j -= 42] = c --/

Nowhere does what happens depend on which topological sort is chosen.  However, if we instead did

    a[++i] = b[i -= 42] = c;

then we have a problem, since the indexes used depend on which is evaluated first: (++i) or (i -= 42).


OST, I think what you're thinking is that, since the evaluation associativity of (a + b + c) is specified as unspecified, the same holds for = and other operators.  The bit I can find is

http://www.digitalmars.com/d/portability.html
"a + b + c
can be evaluated as (a + b) + c, a + (b + c), (a + c) + b, (c + b) + a, etc. Parentheses control operator precedence, parentheses do not control order of evaluation."

That is, the spec is effectively making an exception for + to the operator precedence implied by the grammar.  Unless I've missed it, the spec doesn't make any exception remotely resembling this for = or other operators.  (Strictly speaking, this isn't actually an exception, rather a possibility for optimisation.)

Stewart.



More information about the Digitalmars-d mailing list