Operator precedence problem
Rustom Mody
rustompmody at gmail.com
Mon Jun 6 13:14:36 EDT 2016
On Monday, June 6, 2016 at 7:27:18 PM UTC+5:30, Random832 wrote:
> On Mon, Jun 6, 2016, at 01:46, Lawrence D’Oliveiro wrote:
> > On Monday, June 6, 2016 at 4:06:20 AM UTC+12, Uri Even-Chen wrote:
> > > Never write expressions, such as 2 ** 3 ** 2 or even 2 * 4
> > > + 5, without parentheses.
> >
> > That leads to the code equivalent of
> > <http://i.dailymail.co.uk/i/pix/2011/10/13/article-2048696-03F82C520000044D-302_634x332.jpg>.
>
> Okay, can we settle on, as a principle, "the basic arithmetic operators
> (not to include **) are the only ones whose precedence can be presumed
> to be obvious to all readers, and other expressions may/should have
> parentheses to make it more clear, even when not strictly necessary to
> the meaning of the expression"?
>
> Sure, it's obvious to _me_ that << and >> have higher precedence than &
> and |, and that "and" has a higher precedence than "or", but can I
> assume the other people know this? And I don't know offhand the relative
> precedence of non-conceptually-related groups of operators, except that
> I'm pretty sure "and" and "or" have very low precedence.
>
> [To keep this on-topic, let's assume that this discussion has a goal of
> getting something along the lines of "always/sometimes/never use
> "unnecessary" parentheses" into PEP7/PEP8. Speaking of, did you know
> that C has lower precedence for the bitwise operators &^| than for
> comparisons? That was something that tripped me up for a very long time
> and undermined my confidence as to other aspects of the bitwise
> operators]
Kernghan/Thomson/Ritchie (dont remember which) actually admitted to the
fact that these precedences are wrong
I believe there are necessary (maybe not sufficient) conditions for a
precedence table
▲ : A × A → B
■ : B × B → C
then ■ should be lower than ▲
because otherwise
(x ■ y) ▲ z comes out type-wrong
Of course these rules are usually more informal than rigorous -- both in
programming and in math
eg in C there is really not much of any type but int
Still if we informally treat
< : A × A → Bool (A is some kind of numeric)
+,* : A × A → A
&&, || : Bool × Bool → Bool
then it follows that
+,*
< <= etc
&& ||
is the natural precedence table
The mistake that C creators made was to treat bitwise operators as
*logical* rather than as *arithmetic*
More information about the Python-list
mailing list