Bitwise or

I would like to figure out, if the value of a variable is either one or two.
The strange thing is that the result of x == 1 is of type Bool, but bitwise or, "|" makes a difference between (x == 1) and x == 1, is this an expected behaviour?

x = 1
x == 1 | x == 2       # result false
(x == 1) | (x == 2)   # result true
b = x == 1            # b is of type "Bool"
println(typeof(b))

Yes, this is expected. | has higher precedence than ==, which means your second example is parsed as if it were written like (x == (1 | x) == 2).

See also

https://docs.julialang.org/en/v1/manual/mathematical-operations/#Operator-Precedence-and-Associativity

Additionally, == between integers and booleans is well defined, since true == 1 and false == 0.

2 Likes

Quick way to see the precedence:

julia> Meta.@lower x == 1 | x == 2
:($(Expr(:thunk, CodeInfo(
    @ none within `top-level scope`
1 ─ %1 = 1 | x
│   %2 = x == %1
└──      goto #3 if not %2
2 ─ %4 = %1 == 2
└──      return %4
3 ─      return false
))))
3 Likes

Thanks both for your explanations!!! :slight_smile: