Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of operations (== vs. not)

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.

like image 938
Mike Avatar asked Nov 07 '16 22:11

Mike


People also ask

IS and or OR evaluated first?

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-- .

Which operator is having the lowest precedence?

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.

Which operator has highest precedence in?

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.

Which has higher precedence multiplication or division?

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.


2 Answers

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.

like image 190
Mud Avatar answered Oct 09 '22 02:10

Mud


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'.

like image 26
user207421 Avatar answered Oct 09 '22 03:10

user207421