On 2/13/15 9:01 AM, anonymous wrote:
On Friday, 13 February 2015 at 13:25:55 UTC, Steven Schveighoffer wrote:
Yes, the operator precedence (curiously not defined in the spec) is here:
http://wiki.dlang.org/Operator_precedence
Conditional operator is above assignment operators.
It's specified through the grammar [1]:
----
AssignExpression:
ConditionalExpression
ConditionalExpression = AssignExpression
[...]
ConditionalExpression:
OrOrExpression
OrOrExpression ? Expression : ConditionalExpression
----
The third operand of ConditionalExpression cannot be an AssignExpression
without parentheses.
So `foo ? bar : baz = qux` can only be interpreted as `(foo ? bar : baz)
= qux`.
[1] http://dlang.org/expression.html
Right, but C++ seems to treat it differently, but has the same order of
precedence. It seems that C++ can do lvalues as a result of assignment,
but for some reason it doesn't do the same as D.
Indeed, if you do:
(a < 10) ? 5 : a = 1;
In D, this results in an error, in C++, this just results in the rvalue 5.
OK, so I just looked for more information, and found that in some
references, the ?: is given the same precedence as the assignment
operator (and ordered right to left), which would explain the behavior.
So likely the wikipedia reference is just wrong.
e.g.: http://en.cppreference.com/w/cpp/language/operator_precedence
Walter (or other language gurus), any reason that D does it this way?
The C++ way seems more natural to me.
-Steve