Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: =?UTF-8?B?Sm9zaHVhIENyYW5tZXIg8J+Qpw==?= Newsgroups: comp.lang.java.programmer Subject: Re: verifying precedence Date: Thu, 01 May 2014 10:35:34 -0500 Organization: A noiseless patient Spider Lines: 52 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Thu, 1 May 2014 15:35:53 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="8b6ddcc38ecbed2f71b30fabadb8aa0b"; logging-data="19351"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18/1gY7kv1IQOt7EhU+vrajWPdR8l1uLPc=" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Thunderbird/29.0 In-Reply-To: Cancel-Lock: sha1:EthJYrK4uNM7bEq6Z9XIRC9+mKo= Xref: csiph.com comp.lang.java.programmer:28333 On 5/1/2014 7:04 AM, Leif Roar Moldskred wrote: > Roedy Green wrote: >> >> You could consult a precedence table, but you could misinterpret it. >> Java's rules of precedence and association are quite complicated. >> > > "Practical Programming in C" summed up the precedence rules in C > thusly: > > " Precedence Operator > 1. * / % > 2. + - > > Put parantheses around everything else." > > If the meaning of your code depends on the particulars of operator > precedence beyond the very obvious rules above, rewrite it so that it > doesn't. (The same holds for the difference between ++i and i++.) That's not quite the right rules, but probably because it's ignoring half the operators in the first place. I'd remember it as: 1. Unary operators [includes parentheses] 2. * / % 3. + - 4. Relational (<, >, ==, etc.) 5. Logical (&&, ||) 6. ?: 7. = and op= The position of shift and bitwise operators is the part I can never remember: C (by accident of history [1]) put the bitwise below relational operators instead of above it (so you have to say (x & mask) == mask instead of x & mask == mask). Some descendants fixed the issue, while others did not, so as someone who regularly uses several different languages, I can never remember if the language I'm in fixed the precedence or not. Note that the table I give glides over the binding of a few operators (x++ and ++x are different levels, as are < and ==), but in terms of remembering where I need to put parentheses, it's sufficient. [1] Logical, short-circuit and and or came much later. That's why the and pseudo-keyword maps to &, not &&. Arguably, when the logical operators had been introduced, the bitwise operators ought to have been moved in precedence, but maybe the authors of C didn't want to risk such a breaking change at that time. -- Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth