Operation Priority of Logical Operators in Common Languages

In C++, the priority of logical operators from high to low is:

  1. ! (logical NOT)
  2. && (logical AND)
  3. || (logical OR)

It should be noted that, like other operators in C++, logical operators also have associativity, that is, when multiple operators of the same level appear, their calculation order is determined by their associativity. In C++, the associativity of logical operators is from left to right, that is, the operand on the left is calculated first.

For example, for the expression

!a && b || c

, and its calculation sequence is:

  1. !a, computes the logical NOT operation, yielding a Boolean value
  2. !a && b, computes the logical AND operation, yielding a Boolean value
  3. !a && b || c, calculate the logical OR operation to get the final Boolean value

If you need to change the calculation order of logical operators, you can use parentheses to clarify the calculation order of expressions. For example, the expression

!(a && b) || c

The logical AND operation is calculated first, and then the logical NOT and logical OR operations are calculated.

Also, the precedence of logical operators is similar in most programming languages, but there are some exceptions. Following are the logical operator precedence for some common programming languages:

  • Java: ! > && > ||
  • Python: not > and > or
  • JavaScript: ! > && > ||
  • Ruby: ! > && > ||
  • PHP: ! > && > ||
  • Swift: ! > && > ||
  • Go: ! > && > ||

Guess you like

Origin blog.csdn.net/weixin_64089259/article/details/130140614