Precedence (Order of Operations)

Last modified by Microchip on 2023/11/09 09:06

In the following table operators grouped together in a section have the same precedence. For example, the first four entries in this table (), [], ., and -> all share the same precedence. These four operators follow the rule of Left-to-Right associativity which is used as a tie breaker when two or more of these appear in the same expression. The next group of operators starting with + and ending with (type) all share the next level of precedence.

OperatorDescriptionAssociativity
( )
[ ]
.
->
Parenthesized Expression
Array Subscript
Structure Member
Structure Pointer
Left - to - Right
+ -
++ - -
! ~
*
&
sizeof
(type)
Unary + and - (Postitive and Negative Signs)
Increment and Decrement
Logical NOT and Bitwise Complement
Dereference (Pointer)
Address of
Size of Expression or Type
Explicit Typecast
Right - to - Left
* / %Multiply, Divide, and ModulusLeft - to - Right
+ -Add and SubtractLeft - to - Right
« »Shift Left and Shift RightLeft - to - Right
< <=
> >=
Less Than and Less Than or Equal To
Greater Than and Greater Than or Equal To
Left - to - Right
== !=Equal To and Not Equal ToLeft - to - Right
&Bitwise ANDLeft - to - Right
^Bitwise XORLeft - to - Right
|Bitwise ORLeft - to - Right
&&Logical ANDLeft - to - Right
||Logical ORLeft - to - Right
?:Conditional OperatorRight - to - Left
=
+= -=
/= *=
%=
«= »=
&= |=
^=
Assignment
Addition and Subtraction Assignments
Division and Multiplication Assignments
Modulus Assignment
Shift Left and Shift Right Assignments
Bitwise AND and OR Assignements
Bitwise XOR Assignment
Right - to - Left
,Comma OperatorLeft - to - Right

When expressions contain multiple operators, their precedence determines the order of evaluation

ExpressionEffective Expression
a - b * ca - (b * c)
a + ++ba + (++b)
a + ++b * ca + ((++b)*c)

If functions are used in an expression, there is no set order of evaluation for the functions themselves.
For example:
x = f() + g()
There is no way to know if f() or g() will be evaluated first. 

Associativity

If two operators have the same precedence, their associativity determines the order of evaluation.

ExpressionAssociativityEffective Expression
x / y % zLeft - to - Right(x / y) % z
x = y = zRight - to - Leftx = (y = z)
~++xRight - to - Left~(++x)

You can rely on these rules, but it is good programming practice to explicitly group elements of an expression by using parentheses.