ความหมาย
Simple if ใช้ executes คำสั่งเมื่อ logical condition เป็นจริง (true) เท่านั้น ไม่มี else branch
Syntax
if (condition) {
// statement(s)
}การทำงาน
- Condition จริง -> ทำคำสั่งใน block -> ต่อไป
- Condition เท็จ -> ข้าม block -> ต่อไป
- Braces {} จำเป็นถ้ามีหลายคำสั่ง แนะนำให้ใช้เสมอ
ตัวอย่างโปรแกรม: ตรวจสอบเลขคี่ (ไม่มี else)
#include <stdio.h>
int main() {
int a;
printf("ป้อนค่า a: ");
scanf("%d", &a);
if (a % 2 == 1) {
printf("a เป็นเลขคี่\\n");
}
// ไม่มี else -> ถ้าเป็นคู่ ไม่พิมพ์อะไร
return 0;
}ผลลัพธ์
Run 1: ป้อนค่า a: 56 (ไม่มี output เพราะ 56 เป็นคู่) Run 2: ป้อนค่า a: 33 a เป็นเลขคี่
เมื่อไหร่ใช้ Simple If
- มีเพียงหนึ่งทางเลือกที่ต้องทำ (action required only when true)
- Validation checks: if (invalid) return error;
- Guard clauses: if (ptr == NULL) return;
- Flag setting: if (condition) flag = 1;
Common Pitfall: Dangling Else
if (a > 0)
if (b > 0)
printf("both positive");
else
printf("a not positive"); // else นี้ pair กับ if (b > 0) ไม่ใช่ if (a > 0)!แก้ไข: ใช้ braces
if (a > 0) {
if (b > 0)
printf("both positive");
} else {
printf("a not positive");
}Best Practices
- ใช้ braces {} เสมอ (ป้องกัน dangling else และง่ายต่อการเพิ่มคำสั่ง)
- Condition ควรอ่านง่าย (positive logic)
- หลีกเลี่ยง assignment ใน condition (if (x = 5) -> bug) ใช้ if (x == 5)
- Static analysis tools ช่วยจับ bug ประเภทนี้ได้