5 ms·
I remember only one huristic: unary operators have higher precedence than others.
by nemonemo 7y ago
I remember only one huristic: unary operators have higher precedence than others.
- jimmaswell 7y agoPEMDAS is pretty easy to remember too. Though for programming the E isn't usually relevant unless it's python.
- csunbird 7y agoIs it PEMDAS or PEDMAS ?
- sdenton4 7y agoLuckily, the M and D commute. (...Over the reals. Your mileage may vary in less exact types. The Surgeon General recommends avoiding division in production code. Regulations vary by state.)
- Avshalom 7y agoyou can still run into problems with chains like 2×3÷4×5 (2×3)÷(4×5) = 6÷20 = 0.3 2×(3÷4)×5 = 10×0.75 = 7.5 ((2×3)÷4)×5 = 7.5
- bena 7y agoEither/or. That's kind of one problem with it, it's less PEMDAS and more P, E, MD, AS. Multiplication and division don't have precedence over each other and neither does addition and subtraction. Both of those go from left to right.
- frosted-flakes 7y agoIt's BEDMAS. B for brackets (which is what parentheses are called in Canada; see also square brackets, curly brackets, and angle brackets).
- OskarS 7y agoOh yeah? What is the correct interpretation of *a.b Is it (*a).b Or *(a.b) Your heuristic says it should be the former. Is it? What about this one: *a->b
- perl4ever 7y agoI certainly always always always used parentheses in situations like these back in the day. More because it was the idiom I learned early, rather than a conscious decision to be risk averse or professional.
- jcranmer 7y agoThe mental precedence list I have is: * Name operators (e.g., a::b, a.b, a->b) * a[b], a(b) expressions * Unary suffix operators (C doesn't have these, but Rust's ? operator applies) * Unary prefix operators * Arithmetic operators, following normal mathematical precedence rules (i.e., a + b / c is a + (b / c), not (a + b) / c). Note that I don't have any mental model of how <<, &, |, ^ compare to each other or the normal {,/,%}; {+,-} rank. Comparison operators * Short-circuit operators (&&, ||) * Ternary operator (?:)--and this one is right-associative. * Assignment operators This list I think is fairly objective, although C and some of its children "erroneously" place bitwise {&,|,^} below comparison operators instead of above them. The difference between suffix and prefix unary operators is somewhat debatable, but it actually does make sense if you think of array access and function call expressions as unary suffix operators instead of binary operators.
- nemonemo 7y agoThose show why I called it a heuristic. With some code similar to yours, I would probably use parentheses unless they are frequent enough to deserve some brain cells.