ความหมายของ Expression
Expression คือการรวม operator และ operand ที่ลดรูปเป็นค่าเดียว (single value)
- Operand: ข้อมูลที่ถูกดำเนินการ (ตัวแปร, ค่าคงที่)
- Operator: สัญลักษณ์บอกการดำเนินการ
ตัวอย่าง: z = 3 + 2 * 1 -> z = 5
ประเภทของ Expressions
| ประเภท | คำอธิบาย | ตัวอย่าง |
|---|---|---|
| Primary | Operand พื้นฐาน: ตัวแปร, ค่าคงที่, (expression) | c = a + (5 * b); |
| Postfix | Operator อยู่หลัง operand | a++, func(), arr[i] |
| Prefix | Operator อยู่หน้า operand | ++a, --b, +a, -a, *ptr |
| Unary | 1 operator, 1 operand | a++, --b, !flag, ~bits |
| Binary | 1 operator, 2 operands | a + b, c - d, x * y |
| Ternary | 1 operator (? :), 3 operands | cond ? exp1 : exp2 |
รายละเอียดแต่ละประเภท
1. Primary Expressions
- Identifiers:
x, count, name - Constants:
10, 3.14, 'A', "hello" - Parenthesized:
(a + b) - Function calls:
sqrt(x) - Array subscript:
arr[i] - Member access:
struct.member, ptr->member
2. Postfix Expressions
- Post-increment/decrement:
i++, i-- - Function call:
func(args) - Array subscript:
arr[index] - Member access:
obj.member, ptr->member - Compound literal (C99):
(int[]){1,2,3}
3. Prefix/Unary Expressions
- Pre-increment/decrement:
++i, --i - Unary plus/minus:
+a, -a - Logical NOT:
!a - Bitwise NOT:
~a - Address-of:
&a - Dereference:
*ptr - Sizeof:
sizeof(int) - Cast:
(float)a
4. Binary Expressions
- Arithmetic:
+, -, *, /, % - Relational:
<, <=, >, >= - Equality:
==, != - Bitwise:
&, |, ^, <<, >> - Logical:
&&, || - Assignment:
=, +=, -=... - Comma:
a, b(evaluate a, then b, result = b)
5. Ternary Expression (Conditional Operator)
condition ? expression_if_true : expression_if_false
ตัวอย่าง: max = (a > b) ? a : b;
ตัวอย่างโปรแกรมสาธิต
#include <stdio.h>
int main() {
int a, b, c, d;
int r, s, t, u, v, z;
printf("ป้อน a,b,c,d: ");
scanf("%d%d%d%d", &a, &b, &c, &d);
r = a++; // Postfix/Unary: r = a, then a++
s = --b; // Prefix/Unary: b--, then s = b
t = a + b; // Binary
u = c - d; // Binary
v = a + (5 * b); // Primary (5*b) + Binary
z = (5 > 3) ? 1 : 0; // Ternary
printf("Unary postfix (a++): %d\\n", r);
printf("Unary prefix (--b): %d\\n", s);
printf("Binary (a+b): %d\\n", t);
printf("Binary (c-d): %d\\n", u);
printf("Primary (a+5*b): %d\\n", v);
printf("Ternary (5>3?1:0): %d\\n", z);
return 0;
}ผลลัพธ์ตัวอย่าง
ป้อน a,b,c,d: 2 3 4 6 Unary postfix (a++): 2 Unary prefix (--b): 2 Binary (a+b): 5 Binary (c-d): -2 Primary (a+5*b): 13 Ternary (5>3?1:0): 1
Operator Precedence (สรุป)
- Postfix: () [] -> . ++ --
- Prefix/Unary: ++ -- + - ! ~ & * sizeof (cast)
- Multiplicative: * / %
- Additive: + -
- Shift: << >>
- Relational: < <= > >=
- Equality: == !=
- Bitwise AND: &
- Bitwise XOR: ^
- Bitwise OR: |
- Logical AND: &&
- Logical OR: ||
- Ternary: ? :
- Assignment: = += -= *= /= %= ...
- Comma: ,