[swift-evolution] Standard operator precedence
Xiaodi Wu
xiaodi.wu at gmail.com
Sat Feb 13 08:32:13 CST 2016
Not sure if this is intentional, a bug, and/or a topic for evolution:
In Swift, bitwise operators seem to have a different precedence in
relation to other operators than they do in (all other?) C-family
languages, at least per documentation. One specific example--this
statement in C:
```
v = v + (v >> 4) & 0x0F0F0F0F;
```
is evaluated in a different order (at least, per documentation) from
this statement in Swift:
```
v = v &+ (v >> 4) & 0x0F0F0F0F
```
In C, C++, C#, Java, Python, Perl, Scala (these are the ones I've just
checked), infix + has higher precedence than infix bitwise &, but in
Swift the bitwise & operator has multiplicative precedence 150 while +
has precedence 140. Meanwhile, bitshift operators << and >> are
documented to have exponentiative precedence 160 in Swift, higher than
* / + -, which is not seen in other languages. Is this an intentional
deviation with some rationale not documented somewhere? Can we change
it back? [I know I can change it on a per-file basis, but the point
here is that, for a C-style language, having different results for
innocuous-looking statements with these operators seems to be a little
too easy a pitfall to step in.]
More information about the swift-evolution
mailing list