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

Nested Switch Case ในภาษา C

โจทย์

เขียนโปรแกรม C ตรวจสอบรหัสผ่าน (password) ตามรหัสผู้ใช้ (user ID) โดยใช้ nested switch case

แนวคิด Nested Switch

  • เขียน switch ภายใน switch อีกชั้น (inner switch ใน outer switch)
  • ค่า case ของ inner และ outer สามารถซ้ำกันได้ (แยก scope)

กฎของ Switch Statement

  • Expression ต้องเป็น integer หรือ character type
  • Case labels ต้องเป็น constant และ unique
  • Case label ต้องลงท้ายด้วย colon (:)
  • ควรมี break ในแต่ละ case (ยกเว้นต้องการ fall-through)
  • default ได้สูงสุด 1 ตัวต่อ switch
  • สามารถ nested ได้หลายชั้น

ตัวอย่างโปรแกรม: ตรวจสอบ User ID และ Password

#include <stdio.h>
int main() {
    int userid, pwd;
    printf("ป้อน User ID: ");
    scanf("%d", &userid);
    switch (userid) {
        case 1234:
            printf("ป้อน Password: ");
            scanf("%d", &pwd);
            switch (pwd) { // Nested switch
                case 0000:
                    printf("Tutorials Point\\n");
                    break;
                default:
                    printf("รหัสผ่านไม่ถูกต้อง\\n");
                    break;
            }
            break;
        default:
            printf("User ID ไม่ถูกต้อง\\n");
            break;
    }
    return 0;
}

ผลลัพธ์ตัวอย่าง

Run 1:
ป้อน User ID: 1234
ป้อน Password: 0000
Tutorials Point
Run 2:
ป้อน User ID: 1234
ป้อน Password: 234
รหัสผ่านไม่ถูกต้อง

ข้อควรระวัง

  • Octal literal: 0000 ใน C คือเลขฐาน 8 (octal) ไม่ใช่เลข 0 ทศนิยม 4 หลัก
  • Input 0000 ด้วย scanf("%d") จะอ่านเป็น 0 (decimal)
  • ควรใช้ string สำหรับ password จริง (รองรับ leading zeros และอักษร)
  • Fall-through: หากไม่มี break จะรัน case ถัดไปต่อ (บางครั้งตั้งใจทำ แต่ควร comment)

ตัวอย่าง Fall-through ที่ตั้งใจ

switch (month) {
    case 1: case 3: case 5: case 7: case 8: case 10: case 12:
        days = 31; break;
    case 4: case 6: case 9: case 11:
        days = 30; break;
    case 2:
        days = 28; break;
}

Best Practices

  • ใช้ default case เสมอสำหรับ error handling
  • Comment // fall through หากตั้งใจไม่ break
  • หลีกเลี่ยง nested switch ลึกเกินไป (ยากอ่าน) -> ใช้ if-else หรือ function แทน
  • พิจารณาใช้ lookup table/array สำหรับ mapping เรียบง่าย