Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!think.com!compass!worley From: worley@compass.com (Dale Worley) Newsgroups: comp.lang.c Subject: Re: The irregularity of the ?: operator Message-ID: Date: 2 May 91 14:48:12 GMT References: Sender: root@compass.com Distribution: comp Organization: Compass, Inc., Wakefield, MA, U.S.A. Lines: 52 In-reply-to: richard@iesd.auc.dk's message of 17 Apr 91 18:37:17 GMT In article 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