I’m wondering why the shift operators (<< and >>), being equivalent to a multiplication and a division respectively, do have less priority than an additive operator, such the “+”.
In other words:
int a = 1 + 2 * 8; //yields 17
whereas:
int a = 1 + 2 << 3; //yields 24
Anyone knows what’s the reason behind this behavior?
NOTE: Please, don’t answer me “because the specs say so”!
Thank you all in advance.
EDIT: I realized that a left-shift can be obtained by summing the left operand by itself. May be this the reason?
The relative priority of arithmetic operators and bitwise operators is irrelevant because you should never be using them together anyway. If you want to treat an integer as an array of bits, then don’t be adding and subtracting it like a number. If you want to treat an integer as a number, then don’t be shifting, or-ing and and-ing it like an array of bits.
Frankly if I had my way there would be no bit shifting operations on integers; you’d have to cast the integer to a BitArray type, that would not have arithmetic on it. The fact that ints are treated as both bit arrays and numbers is an unfortunate design flaw that exists for historical reasons.
The notion that bit shifting is a kind of multiplication and division is a strange one; bit shifting is bit shifting, not multiplication.