Precedence (Order of Operations)
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.
| Operator | Description | Associativity |
|---|---|---|
| ( ) [ ] . -> | 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 Modulus | Left - to - Right |
| + - | Add and Subtract | Left - to - Right |
| « » | Shift Left and Shift Right | Left - 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 To | Left - to - Right |
| & | Bitwise AND | Left - to - Right |
| ^ | Bitwise XOR | Left - to - Right |
| | | Bitwise OR | Left - to - Right |
| && | Logical AND | Left - to - Right |
| || | Logical OR | Left - to - Right |
| ?: | Conditional Operator | Right - 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 Operator | Left - to - Right |
When expressions contain multiple operators, their precedence determines the order of evaluation
| Expression | Effective Expression |
|---|---|
| a - b * c | a - (b * c) |
| a + ++b | a + (++b) |
| a + ++b * c | a + ((++b)*c) |
Associativity
If two operators have the same precedence, their associativity determines the order of evaluation.
| Expression | Associativity | Effective Expression |
|---|---|---|
| x / y % z | Left - to - Right | (x / y) % z |
| x = y = z | Right - to - Left | x = (y = z) |
| ~++x | Right - 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.