Programming Gambas from Zip/OperatorPrecedence

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Operator Precedence[edit | edit source]

In an expression, which part gets worked out first, then which operations are worked out next?

For example, is 2 + 3 * 4 equal to 20 (+ first, * second) or is it 14 (* first, then +)? Multiplication precedes addition, so the expression comes down to 14.

Rules:

  1. Things are worked out before they are compared.
  2. Anything in brackets is worked out first.
  3. The highest priority is changing the sign (–) or reversing true/false with NOT.
  4. Strings are joined before paths are assembled. (& is done before &/).
  5. Powers are done before multiplication or division, which are done before addition or subtraction.
  6. Where there are several operations and they all have the same precedence, the order is left to right but it does not matter because 3 * (4 / 2) is the same as (3 * 4) / 2
  7. Comparisons are worked out before they are ANDed, ORed or XORed with other comparisons.

Examples:

4 ^ 2 * 3 ^ 3 is the same as (4 ^ 2) * ( 3 ^ 3 )

a > 10 AND a < 20 is the same as ( a > 10 ) AND ( a < 20 )

4 * 2 + 3 * 3 is the same as ( 4 * 2 ) + ( 3 * 3 )

4 + 2 = 5 + 1 is the same as ( 4 + 2 ) = ( 5 + 1 )

Programming Gambas from Zip
 ← Formatting OperatorPrecedence Afterword →