The irregularity of the ?: operator
Dale Worley
worley at compass.com
Fri May 3 00:48:12 AEST 1991
In article <RICHARD.91Apr17193717 at euler.iesd.auc.dk> richard at iesd.auc.dk (Richard Flamsholt S0rensen) writes:
expr ::= assignment-expr
expr , assignment-expr
assignment-expr ::= conditional-expr
unary-expr assignment-op assignment-expr
conditional-expr ::= OR-expr
OR-expr ? expr : conditional-expr
The first thing I noticed was a strange irregularity - it seems,
that the third argument to ?: is somewhat restricted. While the second
may be a full expression, the third may only be a conditional-expr
(that is, a ?: construction itself, as in "expr1?x: expr2?y:z").
What you're seeing is just the ordinary way of implementing
precedences. For instance, consider the traditional grammar:
expr ::= term
| expr + term
term ::= factor
| term * factor
factor ::= etc.
The assymmetry in the second rule (expr + term) forces "term + term +
term" to be parsed as "(term + term) + term", because adding two terms
produces an expr, which must be the first argument of +.
In the above grammar, the first argument to conditional-expr is an
OR-expr (the next most restrictive construction), whereas the third
argument is again allowed to be a conditional-expr. This forces
a ? b : c ? d : e
to parse as
a ? b : (c ? d : e)
which is probably what you mean when you write it.
The second argument (the expr between ? and :) is an oddity -- since
it is bracketed by two operators, it can be absolutely any expression
(as () and [] allow), because no ambiguity can arise.
Dale
Dale Worley Compass, Inc. worley at compass.com
--
I know who I am. I'm a figment of my own imagination. And you are?
-- kent-j at cis.ohio-state.edu
More information about the Comp.lang.c
mailing list