Correct parsing of ternary operator.

Steve Emmerson steve at groucho.ucar.edu
Fri Jan 5 02:51:29 AEST 1990


[This is the third time, that I'm aware of, that this topic has come up.]

In the referenced article, lijewski at batcomputer.tn.cornell.edu (Mike
Lijewski) questions whether or not the following statement is legal
since it seems to violate C's rules of precedence:

	c ? c = a : c = b;

It is my understanding that precedence rules are for disambiguating
ambigous sentences, i.e. for chosing one particular way of *generating*
a sentence from amongst alternatives.

Some sentences in classic C (i.e. K&R-1) can be generated in more than
one way; consequently, classic C requires precedence rules in order to
parse them.  In pANS C, however, no precedence rules are required as
each sentence can be generated in only one way (at least for the
grammar listed in K&R-2).

There is only one way to generate the suspect statement above in
classic C; hence, no precedence rules are needed.  The sequence is

	expr ;
	expr ? expr : expr ;
	c ? lval = expr : lval = expr ;
	c ? c = a : c = b ;

In pANS C, the suspect statement *cannot be generated* (due to the
grammar -- not precedence rules).

In summary, precedence rules are a tool of the parser and are needed by
it only to choose between alternative *generation* sequences.  If
there's only one sequence, they don't apply.

Steve Emmerson        steve at unidata.ucar.edu        ...!ncar!unidata!steve



More information about the Comp.lang.c mailing list