8.8 Operator Precedence

Operator precedence determines how operators are grouped, when different operators appear close by in one expression. For example, ‘*’ has higher precedence than ‘+’. Thus, the expression a + b * c means to multiply b and c, and then add a to the product (i.e., a + (b * c)).

You can overrule the precedence of the operators by using parentheses. You can think of the precedence rules as saying where the parentheses are assumed if you do not write parentheses yourself. In fact, it is wise to use parentheses whenever you have an unusual combination of operators, because other people who read the program may not remember what the precedence is in this case. You might forget as well, and then you too could make a mistake. Explicit parentheses will help prevent any such mistake.

When operators of equal precedence are used together, the leftmost operator groups first, except for the assignment operators, which group in the opposite order. Thus, the expression a - b + c groups as (a - b) + c, but the expression a = b = c groups as a = (b = c).

The precedence of prefix unary operators is important when another operator follows the operand. For example, -x^2 means -(x^2), because ‘-’ has lower precedence than ‘^’.

Here is a table of the operators in Octave, in order of decreasing precedence. Unless noted, all operators group left to right.

function call and array indexing, cell array indexing, and structure element indexing

()’ ‘{}’ ‘.

postfix increment, and postfix decrement

++’ ‘--

These operators group right to left.

transpose and exponentiation

'’ ‘.'’ ‘^’ ‘.^

unary plus, unary minus, prefix increment, prefix decrement, and logical "not"

+’ ‘-’ ‘++’ ‘--’ ‘~’ ‘!

multiply and divide

*’ ‘/’ ‘\’ ‘.\’ ‘.*’ ‘./

add, subtract

+’ ‘-

colon

:

relational

<’ ‘<=’ ‘==’ ‘>=’ ‘>’ ‘!=’ ‘~=

element-wise "and"

&

element-wise "or"

|

logical "and"

&&

logical "or"

||

assignment

=’ ‘+=’ ‘-=’ ‘*=’ ‘/=’ ‘\=’ ‘^=’ ‘.*=’ ‘./=’ ‘.\=’ ‘.^=’ ‘|=’ ‘&=

These operators group right to left.