←back to thread

183 points sebg | 2 comments | | HN request time: 0s | source
Show context
benob ◴[] No.43644247[source]
TIL that in python, 1--2==3
replies(1): >>43644397 #
seplox ◴[] No.43644397[source]
It's not a python thing. 1-(-2), distribute the negative.
replies(1): >>43644519 #
qsort ◴[] No.43644519[source]
In most C-like languages that would be a syntax error. E.g. in C and C++ as a rule you tokenize "greedily", "1--2" would be tokenized as "1", "unary decrement operator", "2", which is illegal because you're trying to decerment an rvalue.

Python doesn't have "--", which allows the tokenizer to do something else.

replies(2): >>43645088 #>>43646211 #
1. nyrikki ◴[] No.43645088[source]
In C, that is really because Unary minus (negation) has precedence over binary operations.

    +a - b; // equivalent to (+a) - b, NOT +(a - b)
    -c + d; // equivalent to (-c) + d, NOT -(c + d)

https://en.cppreference.com/w/cpp/language/operator_arithmet...

    +-e; // equivalent to +(-e), the unary + is a no-op if “e” is a built-in type
     // because any possible promotion is performed during negation already
The same doesn't apply to, !! Which is applied as iterated binary operations (IIRC)

I am pretty sure the decriment operator came around well after that quirk was established.

replies(1): >>43645741 #
2. seanhunter ◴[] No.43645741[source]
Peter van der Linden’s book “Expert C Programming” (which is awesome btw) says that one of them (Kernighan, Richie or maybe Ken Thompson I forget) realised early on that the c compiler had the wrong operator precedence for bit twiddling and unary and boolean operators but “at that stage we had a few thousand lines of C code and thought it would be too disruptive to change it”