Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Is this really a difficult precedence issue? It seems quite obvious to me that *foo + 1 parses as (*foo) + 1.

One that has gotten me more than once in Python (I really don’t code Python that much) is “1 + 2 if True else 3”. I keep thinking the parenthesis are “1 + (2 if True else 3)”, but it’s actually (1 + 2). Or am I lying to you and it’s the other way around?! I don’t know, why don’t you go check the Python interpreter :)





Conditional expressions/operators, including e.g. the `?:` ternary operator in C-like languages, typically have about the lowest precedence, higher only than the assignment operators (and the comma operator in C-like languages). It's not just a Python thing; you'll find `+` having higher precedence basically everywhere.

Think of

  x = 1 + 2 if True else 3
like a shorthand for:

  if True:
    x = 1 + 2
  else:
    x = 3
which can be a common pattern in languages that don't really have conditional expressions, like bash.

> Is this really a difficult precedence issue? It seems quite obvious to me that foo + 1 parses as (foo) + 1.

Keep in mind that precedence rules are arbitrary constructs, typically based upon what the rule maker perceived as more convenient. Perceptions will vary from person to person, so there is no objective obvious about them. Heck, there isn't even anything obvious about infix notation (see Forth or Lisp). Or, in the case of unary operators, it isn't obvious that the operator should come before or after the object it is operating on (consider how we negate as a prefix, while factorial is a suffix).


Do you think ++foo + 1 parses as ++(foo + 1)? Despite what you say, this seems obvious to me.

I really dislike relying on precedence when it's more complicated than a few terms of basic arithmetic.

Parentheses are free and makes it absolutely clear what the intention is.


I have often felt this doubt but the only two cases where my intuition was actually wrong was with `new` operators and php's ternary operator

Yes but as I said yesterday on another post, "Yngwie Malmsteen Code".

You could write it clearly by saying foo[1] instead of *(foo+1) which is what they ended up doing, but hey, pointer arithmetic looks complicated and clever, so let's show off with a WEEDLYWEEDLYWEEDLY guitar solo bit of code.


When you are manipulating (mostly) one pointed-to element at a time, and incrementing the pointer itself in between, then that's quite a different mindset compared to using an index into an array. I agree that the subscript operator is the cleanest solution here. My point is just that I think it was missed because it's easy to overlook, rather than because, as you say, someone is deliberately trying to be too clever.



Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: