Logical Operators (ตัวดำเนินการตรรกะ)
ใช้รวม expression 2 ตัวขึ้นไปแบบตรรกะ
Logical AND (&&)
| exp1 | exp2 | exp1 && exp2 |
|---|
| T | T | T |
| T | F | F |
| F | T | F |
| F | F | F |
Short-circuit: ถ้า exp1 เป็น False จะไม่ evaluate exp2
Logical OR (||)
| exp1 | exp2 | exp1 || exp2 |
|---|
| T | T | T |
| T | F | T |
| F | T | T |
| F | F | F |
Short-circuit: ถ้า exp1 เป็น True จะไม่ evaluate exp2
Logical NOT (!)
ตัวอย่าง Logical Operators
| Operator | คำอธิบาย | ตัวอย่าง (a=10,b=20,c=30) | ผลลัพธ์ |
|---|
| && | Logical AND | (a>b) && (a| (F) && (T) = 0 | |
| || | Logical OR | (a>b) || (a<=c) | (F) || (T) = 1 |
| ! | Logical NOT | !(a>b) | !(F) = 1 |
ตัวอย่างโปรแกรม
#include <stdio.h>
int main() {
float a = 0.5, b = 0.3, c = 0.7;
printf("%d\\n", (a < b) && (b > c)); // 0
printf("%d\\n", (a >= b) && (b <= c)); // 1
printf("%d\\n", (a == b) || (b == c)); // 0
printf("%d\\n", (b >= a) || (a == c)); // 0
printf("%d\\n", (b <= c) && !(c >= a)); // 0
printf("%d\\n", !(b <= c) || (c >= a)); // 1
return 0;
}ผลลัพธ์
0
1
0
0
0
1
Assignment Operators (ตัวดำเนินการกำหนดค่า)
ประเภท
- Simple assignment: =
- Compound assignment: +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=
ความหมาย
| Operator | เทียบเท่า | ตัวอย่าง |
|---|
| a += 5 | a = a + 5 | a = 10 -> 15 |
| a -= 5 | a = a - 5 | a = 10 -> 5 |
| a *= 5 | a = a * 5 | a = 10 -> 50 |
| a /= 5 | a = a / 5 | a = 10 -> 2 |
| a %= 5 | a = a % 5 | a = 10 -> 0 |
ตัวอย่างโปรแกรม: Compound Assignment
#include <stdio.h>
int main() {
int i;
char a = 'h'; // ASCII 104
printf("ป้อนค่า i: ");
scanf("%d", &i);
printf("ASCII ของ '%c' = %d\\n", a, a);
a += 5; // 104 + 5 = 109 -> 'm'
printf("หลัง += 5: '%c' = %d\\n", a, a);
a *= a + i; // 109 * (109 + i)
printf("หลัง *= a+i: %d\\n", a);
a *= 3;
printf("หลัง *= 3: %d\\n", a);
a /= 2;
printf("หลัง /= 2: %d\\n", a);
a %= 4;
printf("หลัง %%= 4: %d\\n", a);
return 0;
}ผลลัพธ์ตัวอย่าง
ป้อนค่า i: 3
ASCII ของ 'h' = 104
หลัง += 5: 'm' = 109
หลัง *= a+i: -80 (overflow! int16 หรือคำนวณผิด)
หลัง *= 3: 16
หลัง /= 2: 8
หลัง %= 4: 0
หมายเหตุ: ผลลัพธ์อาจต่างไปตามขนาด int และ overflow behavior
ข้อควรระวัง
- Compound assignment evaluate variable เพียงครั้งเดียว:
a[i++] += 1 != a[i++] = a[i++] + 1 - Precedence ต่ำกว่าส่วนใหญ่:
a += b * c คือ a += (b * c) - Type conversion ตาม usual arithmetic conversions