Precedence Question - (nf)

jas at druxy.UUCP jas at druxy.UUCP
Fri Feb 24 08:21:47 AEST 1984

smu!pedz suggests (among other things) that

foo ? cow = bell : dong

is not a legal C expression, and says that the VAX C compiler
erroneously accepts it because it is a bottom-up compiler generated
by yacc, as opposed to a recursive-descent compiler, which would
(correctly, he contends) reject the expression.  What follows
is an excerpt from a response I mailed to him:

I'm not sure what top-down versus
bottom-up parsing has to do with it.  The C grammar as published
in Kernighan and Ritchie is neither LALR(1) nor LL(1); it is, in
fact, highly ambiguous, and uses operator precedence rules to
disambiguate.  It is possible to write both top-down and bottom-up
parsers that either accept or do not accept "foo ? cow = bell : dong".
I contend, though, that only parsers that DO accept it are correct.
Here is why:

The relevant production from the C grammar is:

expression --> expression ? expression : expression

"cow = bell" is an expression, and thus legal between the '?' and the
':'.  The precedence of the operators is irrelevant here, because
this is not an ambiguous construct: i.e., there is no syntactically
correct way to group this construct other than

( foo ? ( cow = bell ) : dong )

Operator precedence only enters into the picture when the above expression
is combined with others in a way that would be ambiguous, were it not
for precedence rules.  For example:

bar = foo ? cow = bell : dong

Here, without precedence rules, there would be two possible parses:

(1)  ( ( bar = foo ) ? ( cow = bell ) : dong )   and
(2)  ( bar = ( foo ? ( cow = bell ) : dong ) )

We need to know that assignment has a lower precedence than ?: to
determine that (2) is the correct parse.

Jim Shankland

More information about the Comp.lang.c mailing list