[comp.lang.c] The irregularity of the ?: operator

gwyn@smoke.brl.mil (Doug Gwyn) (05/02/91)

In article <RICHARD.91Apr17193717@euler.iesd.auc.dk> richard@iesd.auc.dk (Richard Flamsholt S0rensen) writes:
>  According to the syntax,
>	x == 0 ? c = 2 : c = 4;
>  is illegal, because it is parsed as
>	(x == 0 ? c = 2 : c) = 4;
>  Everyone (well, almost - otherwise there wouldn't be any discussions
>here on c.l.c :-) has acknowlegded, that this is correct.

Then "everyone" is wrong.

The LHS of an assignment expression must be a unary expression;
thus, your suggested parse is incorrect.

The example is unparsable according to the official C grammar.
By judicious addition of parentheses you could make it parse in
at least four distinct ways.

worley@compass.com (Dale Worley) (05/02/91)

In article <RICHARD.91Apr17193717@euler.iesd.auc.dk> richard@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@compass.com
--
I know who I am.  I'm a figment of my own imagination.  And you are?
-- kent-j@cis.ohio-state.edu