Operator Precedence (ลำดับความสำคัญ)
กำหนดลำดับการประเมินค่าเมื่อมีออเปอเรเตอร์มากกว่า 1 ตัวในนิพจน์ ออเปอเรเตอร์ที่มี Precedence สูงกว่าจะถูกประเมินก่อน
Operator Associativity (การจับกลุ่ม)
กำหนดลำดับการประเมินเมื่อออเปอเรเตอร์มี Precedence เท่ากัน Left-to-Right หรือ Right-to-Left
ตาราง Precedence และ Associativity (เรียงจากสูงไปต่ำ)
| Precedence | Operators | ความหมาย | Associativity |
|---|---|---|---|
| 1 | () [] -> . | Function call, Array access, Struct member | Left to Right |
| 2 | ! ~ + - ++ -- & * sizeof (type) | Unary operators | Right to Left |
| 3 | * / % | Multiply, Divide, Modulo | Left to Right |
| 4 | + - | Add, Subtract | Left to Right |
| 5 | << >> | Bitwise shift | Left to Right |
| 6 | < <= > >= | Relational | Left to Right |
| 7 | == != | Equality | Left to Right |
| 8 | & | Bitwise AND | Left to Right |
| 9 | ^ | Bitwise XOR | Left to Right |
| 10 | | | Bitwise OR | Left to Right |
| 11 | && | Logical AND | Left to Right |
| 12 | || | Logical OR | Left to Right |
| 13 | ?: | Ternary conditional | Right to Left |
| 14 | = *= /= %= += -= &= ^= |= <<= >>= | Assignment | Right to Left |
| 15 | , | Comma operator | Left to Right |
ตัวอย่าง
ในนิพจน์ a = b + c * d : * มี precedence สูงกว่า + ดังนั้นคำนวณ c*d ก่อน แล้วบวก b แล้ว assign ให้ a