บทความนี้จะพูดถึงการใช้ switch case โดยมีรูปแบบคือ
โค้ด: เลือกทั้งหมด
switch (ตัวแปร)
{ case ค่าคงที่ : ชุดคำสั่ง;
case ค่าคงที่ : ชุดคำสั่ง;
.
.
.
default : ชุดคำสั่ง;
ยกตัวอย่างเช่น
โค้ด: เลือกทั้งหมด
#include<stdio.h>
int main ()
{
int num = 3;
switch (num)
{
case 1: printf("one"); break;
case 2: printf("two"); break;
case 3: printf("three"); break;
default: printf("empty"); break;
}
return 0;
}
three
เพราะกำหนดให้ตัวแปร num มีค่าเป็น 3 ซึ่งตรงกับ case 3
***หากไม่ใส่คำสั่ง break ด้านหลัง case จะทำให้โปรแกรมทำตามชุดคำสั่งที่อยู่หลัง case นั้น ๆ ทั้งหมด
ยกตัวอย่างเช่น
โค้ด: เลือกทั้งหมด
#include<stdio.h>
int main ()
{
int num = 2;
switch (num)
{
case 1: printf("one\n");
case 2: printf("two\n");
case 3: printf("three\n");
default: printf("empty\n");
}
return 0;
}
two
three
empty
เนื่องจากไม่มี break จึงทำให้โปรแกรมทำการแสดงผลชุดคำสั่งใน case 3 แล้ว default ด้วย
บทความที่เกี่ยวข้อง
การเขียน if/else ในภาษา C