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

C++ Operators: Precedence และ Associativity


ความหมาย

Operator Precedence กำหนดการจัดกลุ่มของ terms ในนิพจน์

Associativity กำหนดว่าออเปอเรเตอร์ที่มี precedence เท่ากันจะจัดกลุ่มอย่างไรเมื่อไม่มีวงเล็บ ส่งผลต่อลำดับการประเมินค่า

ตัวอย่าง

x = 7 + 3 * 2; ค่า x จะเป็น 13 ไม่ใช่ 20 เพราะ * มี precedence สูงกว่า + ทำให้คูณ 3*2 ก่อน แล้วค่อยบวก 7

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

CategoryOperatorAssociativity
Postfix() [] -> . ++ --Left to right
Unary+ - ! ~ ++ -- (type)* & sizeofRight to left
Multiplicative* / %Left to right
Additive+ -Left to right
Shift<< >>Left to right
Relational< <= > >=Left to right
Equality== !=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?:Right to left
Assignment= += -= *= /= %= >>= <<= &= ^= |=Right to left
Comma,Left to right