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

Operator Precedence และ Associativity ใน C

บทนำ

Operator precedence กำหนดการจัดกลุ่มพจน์ในนิพจน์และตัดสินใจว่าจะประเมินนิพจน์อย่างไร Operator บางตัวมี precedence สูงกว่า เช่น * สูงกว่า +

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

ตาราง precedence (สูงสุดอยู่บนสุด):

Category Operator Associativity
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

ตัวอย่างโค้ด

#include <stdio.h>
int main() {
    int a = 20, b = 10, c = 15, d = 5, e;
    e = (a + b) * c / d; // (30 * 15) / 5
    printf("Value of (a + b) * c / d is : %d\n", e);
    e = ((a + b) * c) / d; // (30 * 15) / 5
    printf("Value of ((a + b) * c) / d is : %d\n", e);
    e = (a + b) * (c / d); // 30 * (15/5)
    printf("Value of (a + b) * (c / d) is : %d\n", e);
    e = a + (b * c) / d; // 20 + (150/5)
    printf("Value of a + (b * c) / d is : %d\n", e);
    return 0;
}

ผลลัพธ์

Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50