- อย่าลืม break; ( นอกจากจะตั้งใจให้ทำงานอย่างนั้น )
- ถ้าไม่มี default โปรแกรมก็จะออกจาก switch โดยไม่ทำอะไร (หากไม่ตรงเคสใดเคสหนึ่ง)
- ใช้ switch case เพื่อทำให้โค๊ดดูง่ายขึ้น แทนที่จะเป็น if-else-if-else….. ( if – else ladder )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int main(void) | |
{ | |
setbuf(stdout,NULL); | |
int choice; | |
printf("Enter number between 1 - 5 : "); | |
scanf("%d",&choice); | |
// if(choice==1) printf("Good \n"); | |
// else if(choice==2) printf("Excellent \n"); | |
// else if(choice==3) printf("Perfect \n"); | |
// else if(choice==4) printf("Fantastic \n"); | |
// else if(choice==5) printf("Marvelous \n"); | |
// else printf("You are not listening to me\n"); | |
switch(choice) | |
{ | |
case 1 : printf("Good \n"); break; | |
case 2 : printf("Excellent \n");break; | |
case 3 : printf("Perfect \n");break; | |
case 4 : printf("Fantastic \n");break; | |
case 5 : printf("Marvelous \n");break; | |
default : printf("You are not listening to me\n"); | |
} | |
return 0; | |
} |