Language Design: Binary Operators are Overused
Published on 2019-09-21.
TL;DR: Use methods.
Many languages provide binary operators, usually for operations on numbers (addition, multiplication), bits (shifts) and boolean values.
The problem with <<
, >>
, >>>
The problem with %
In most languages the %
operator implements a remainder operation, not a modulo operation
- remainder: has the same sign as the dividend
- modulo: has the same sign as the divisor
remainder | modulo | |
---|---|---|
+4 % +3 | 1 | 1 |
-4 % +3 | -1 | 1 |
+4 % -3 | 1 | -1 |
-4 % -3 | -1 | -1 |
There are multiple possible implementations of remainder and modulo, with no clear winner
At least five approaches are known12:
- Remainder of truncated division
- Remainder of floored division
- Remainder of ceiling division
- Remainder of euclidean division
- Remainder of rounded division