switch statement ให้ตัวแปรถูกทดสอบความเท่ากับรายการค่า แต่ละค่าเรียกว่า case ตัวแปรที่ switch on จะถูกตรวจสอบแต่ละ switch case
Syntax ของ switch statement ใน C:
switch(expression) { case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : /* Optional */ statement(s); }กฎของ switch statement:
expression ต้องเป็น integral หรือ enumerated type หรือ class type ที่มี single conversion function ไป integral/enumerated type
สามารถมี case statements จำนวนเท่าไรก็ได้ แต่ละ case ตามด้วยค่าเปรียบเทียบและ colon
constant-expression ต้องเป็น data type เดียวกับตัวแปรใน switch และต้องเป็น constant หรือ literal
เมื่อตัวแปรเท่ากับ case คำสั่งหลัง case นั้นจะ execute จนกว่าจะเจอ break
เมื่อเจอ break switch จบ และ control กระโดดไปบรรทัดถัดไปหลัง switch
ไม่ทุก case ต้องมี break หากไม่มี control จะ fall through ไป case ถัดไปจนกว่าจะเจอ break
switch สามารถมี default case ได้ (optional) ต้องอยู่ท้าย switch ใช้เมื่อไม่มี case ไหน true ไม่ต้องมี break ใน default
ตัวอย่างโค้ด
#include <stdio.h> int main () { /* local variable definition */ char grade = 'B'; switch(grade) { case 'A' : printf("Excellent!\n" ); break; case 'B' : case 'C' : printf("Well done\n" ); break; case 'D' : printf("You passed\n" ); break; case 'F' : printf("Better try again\n" ); break; default : printf("Invalid grade\n" ); } printf("Your grade is %c\n", grade ); return 0; }ผลลัพธ์
Well done Your grade is B