Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Operator Precedence และ Associativity ในภาษา C


Operator Precedence (ลำดับความสำคัญ)

กำหนดลำดับการประเมินค่าเมื่อมีออเปอเรเตอร์มากกว่า 1 ตัวในนิพจน์ ออเปอเรเตอร์ที่มี Precedence สูงกว่าจะถูกประเมินก่อน

Operator Associativity (การจับกลุ่ม)

กำหนดลำดับการประเมินเมื่อออเปอเรเตอร์มี Precedence เท่ากัน Left-to-Right หรือ Right-to-Left

ตาราง Precedence และ Associativity (เรียงจากสูงไปต่ำ)

PrecedenceOperatorsความหมายAssociativity
1() [] -> .Function call, Array access, Struct memberLeft to Right
2! ~ + - ++ -- & * sizeof (type)Unary operatorsRight to Left
3* / %Multiply, Divide, ModuloLeft to Right
4+ -Add, SubtractLeft to Right
5<< >>Bitwise shiftLeft to Right
6< <= > >=RelationalLeft to Right
7== !=EqualityLeft to Right
8&Bitwise ANDLeft to Right
9^Bitwise XORLeft to Right
10|Bitwise ORLeft to Right
11&&Logical ANDLeft to Right
12||Logical ORLeft to Right
13?:Ternary conditionalRight to Left
14= *= /= %= += -= &= ^= |= <<= >>=AssignmentRight to Left
15,Comma operatorLeft to Right

ตัวอย่าง

ในนิพจน์ a = b + c * d : * มี precedence สูงกว่า + ดังนั้นคำนวณ c*d ก่อน แล้วบวก b แล้ว assign ให้ a