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

Nested If-Else Statement ในภาษา C

ความหมาย

Nested if-else คือ if statement ที่อยู่ภายใน if หรือ else อีกชั้น ใช้สำหรับตรวจสอบเงื่อนไขแบบลำดับชั้น (hierarchical conditions)

Syntax

if (condition1) {
    if (condition2)
        stmt1;
    else
        stmt2;
} else {
    if (condition3)
        stmt3;
    else
        stmt4;
}

ตัวอย่างที่ 1: หาค่าสูงสุดของ 3 ตัวเลข

#include <stdio.h>
int main() {
    int a, b, c;
    printf("ป้อนค่า a,b,c: ");
    scanf("%d%d%d", &a, &b, &c);
    if ((a > b) && (a > c)) {
        if (a > c)  // redundant: already checked
            printf("%d มากที่สุด\\n", a);
        else
            printf("%d มากที่สุด\\n", c);
    } else {
        if (b > c)
            printf("%d มากที่สุด\\n", b);
        else
            printf("%d มากที่สุด\\n", c);
    }
    return 0;
}

ผลลัพธ์

ป้อนค่า a,b,c: 3 5 8
8 มากที่สุด

หมายเหตุ: โค้ดตัวอย่างมี redundancy (ตรวจสอบ a>c สองครั้ง) ควรเขียนใหม่ให้กระชับ

ตัวอย่างที่ 2: ตรวจสอบบวก/ลบ/ศูนย์

#include <stdio.h>
int main() {
    int num;
    printf("ป้อนตัวเลข: ");
    scanf("%d", &num);
    if (num > 0) {
        printf("%d เป็นบวก\\n", num);
    } else if (num < 0) {
        printf("%d เป็นลบ\\n", num);
    } else {
        printf("%d เป็นศูนย์\\n", num);
    }
    return 0;
}

ผลลัพธ์

Run 1:
ป้อนตัวเลข: 23
23 เป็นบวก
Run 2:
ป้อนตัวเลข: -56
-56 เป็นลบ

Flowchart Logic

```

        if (num > 0)
           /        \
        True       False
         |           |
    print +      if (num < 0)
                /       \
             True      False
              |          |
         print -     print 0
```

Else-If vs Nested If

ตัวอย่างที่ 2 จริงๆ เป็น else-if ladder ไม่ใช่ nested if แบบแท้ (ซึ่งจะเป็น if ใน if ใน else...)

Nested If แบบแท้ (True Nested)

if (condition1) {
    if (condition2) {
        // ทำเมื่อ condition1 และ condition2 จริง
    } else {
        // ทำเมื่อ condition1 จริง แต่ condition2 เท็จ
    }
} else {
    if (condition3) {
        // ทำเมื่อ condition1 เท็จ แต่ condition3 จริง
    } else {
        // ทำเมื่อ condition1 และ condition3 เท็จ
    }
}

Best Practices

  • ใช้ braces {} ทุกครั้ง แม้ single statement (ป้องกัน bug)
  • Limit nesting depth (ไม่เกิน 3-4 ระดับ) -> extract to functions
  • ใช้ early return/continue เพื่อลด nesting (guard clauses)
  • Comment ปิด block } // end if (condition)