precedence of ?: (was: precedence of && (was: precedence of ?:))

Dave Decot decot at hpisod2.HP.COM
Fri Sep 15 17:29:13 AEST 1989


> I don't find the grammar especially "convoluted"; in fact it's
> relatively straightforward.  The reason for the several types of
> expression is precisely to reflect the correct precedence without
> requiring precedence to be provided by means outside the grammar.

Note that it also renders invalid several classes of expression that
were completely correct in K&R I.  The changes to the grammar require
conforming compilers to reject (or at least warn about) such expressions,
because they are now syntax errors.  For instance, consider:

    double five, three;

	five = 2.0 +  three = 3.0;

Although I grant that it seems ambiguous, it has two valid parses according
to K&R I's grammar (ignoring its precedence rules, for the moment):

    (five = 2.0) + (three = 3.0);	/* somewhat silly */
 or
    (five = (2.0 + (three = 3.0)));	/* more likely what was intended */

The second of these above is the correct interpretation when using the
precedence rules to resolve ambiguity (the only moral use of precedence
rules as far as I'm concerned).

Another interesting effect of the Standard's grammar is that:

    k = (!y ? 0 : t = 1);

is valid, but

    k = (y ? t = 1 : 0);

is a syntax error, although it had a single unambiguous parse in K&R I.

The kinds of valid expression are different for the two right-hand
operands of the ?: operator.

Dave



More information about the Comp.lang.c mailing list