If you want to minimize the need for parentheses
Let's typical use case of bitshift/masking operations.
Bit arrays
Suppose that you have a bit array class, allowing an integer (or array of integers) to be treated as an array of bits. It provides the operations:
- get
bitarray[i]
→ if ((backing_int & (1 << i)) != 0)
- set
bitarrary[i] = value
→ backing_int = (backing_int & ~(1 << i)) | (value << i)
To make these work without parentheses, you would need the precedence order:
- Shifts (
<<
and >>
)
- NOT (
~
)
- AND (
&
)
- OR (
|
)
- Relationals (
==
, !=
, etc.)
Note that I only used left shift (<<
), not right shift (>>
), but since these are parallel and inverse operators, similar to +
and -
, it would be weird to not have them at the same precedence level.
Also, I didn't include XOR (^
) in my example. If you think of XOR as being a one-bit addition (with the carry bit ignored), then it makes sense to place it below AND (which is a one-bit multiplication). If you think of XOR as being a Boolean !=
operator, it makes sense to treat them at the same level as relationals — if you put relationals below OR, as I have done.
UTF-8 decoding
The following line of C(++) code decodes a 4-byte UTF-8 sequence to the corresponding Unicode code point (after the validity check has been done):
code_point = ((bytes[0] & 7) << 18) | ((bytes[1] & 0x3F) << 12) | ((bytes[2] & 0x3F) << 6) | (bytes[3] & 0x3F);
You could make the parentheses unnecessary by using the precedence order:
- AND (
&
)
- Shifts (
<<
, >>
)
- OR (
|
)
Note that this switches the relative precedence of AND and shifting compared to the previous example.
If you want to minimize confusion
As @kaya3 pointed out, if you use the C syntax for operators, people will expect them to work the same as in C. Just as if you allow C-style ;
, people will expect statement termination semantics to be the same as in C — to the confusion of JavaScript developers.
So, if you're committed to the symbols <<
, >>
, ~
, &
, |
. and ^
, it would probably be a good idea to keep C's precedence hierarchy for them.
If you decide to spell the operators differently (e.g., the word-like lshift
, rshift
, not
, and
, or
, and xor
), then this argument might not apply as much.