Does anyone know why "boolean not" has higher precedence than ==
in order of operations for most programming languages?
In mathematical logic/model theory, isn't it the other way around? I recently wrote the following in Lua:
if not 1 == 2 then
print("hi")
end
It wasn't printing "hi" because of the order of operations between not and ==
, which seems bizarre to me.
The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .
LOWEST PRECEDENCE The compound logical operators, &&, ||, -a, and -o have low precedence. The order of evaluation of equal-precedence operators is usually left-to-right.
Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom.
Multiplication has the same precedence as division, but multiplication and division have higher precedence than addition and subtraction have. The multiplication takes place first, the value is added to B, and then the result is assigned to A.
There's never a need to negate a relational operator because each one has an opposite operator. For instance, we have both equality and inequality operators (your example could have been written 1 ~= 2
). Unary operators in most programming languages have the highest precedence, because most of the time that results in code that reads more like natural language.
For instance, not green and not blue
should mean "neither green nor blue". A very low precedence for not
would turn that into something like not (green and not blue)
which is a lot harder to make sense of.
You need to distinguish between not 1 == 2
and not (1 == 2)
. The latter behaves as you expect; the former is a unary not
applied to 1
only, which probably produces zero.
This is not different from 'mathematical/model theory'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With