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

Tom Karzes karzes at mfci.UUCP
Tue Sep 19 05:37:37 AEST 1989


In article <2550103 at hpisod2.HP.COM> decot at hpisod2.HP.COM (Dave Decot) writes:
>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.

Wrong, you've got it backwards.

As someone else mentioned, it's easy to permit any expression between the
? and the : because they are paired and must be properly nested.  Presumably
most C compilers have always allowed arbitrary expressions between the ? and
the :, so the standard allows it as well (although the lack of symmetry
between the true and false cases is somewhat annoying).

As for the first and last operands, at most one of them can be an
unparenthesized ?: expression, since permitting both to be would
introduce an ambiguity.  For example:

    a ? b : c ? d : e

could be:

    (a ? b : c) ? d : e

or it could be:

    a ? b : (c ? d : e)

The latter is more intuitive and useful since it permits else-if chains
without having to stack up parentheses, and this is the correct
interpretation according to the ANSI C standard.  It is also the
interpretation used by correct K&R C compilers, which require ?:
operators to group right-to-left.

Note that there was a mistake in the version of the C reference manual
appearing in some early editions of K&R, in which ?: expressions were
said to group left-to-right.  From section 18.1:

    Binary operators and the conditional operator all group left-to-right,
    and have priority decreasing as indicated:

However, the ?: operator is correctly described in section 7.13 of the
same C reference manual:

    Conditional expressions group right-to-left.

It is also described correctly in the table in section 2.12 of K&R (the
book, not the reference manual).  And of course, ?: groups right-to-left
in the pcc.

Later versions of the C reference manual corrected the error:

    The conditional operator groups right to left.



More information about the Comp.lang.c mailing list