Interesting facts about switch statement in C
Switch เป็นคำสั่งควบคุมที่อนุญาตให้ค่าเปลี่ยนการควบคุมการดำเนินการ ต่อไปนี้เป็นข้อเท็จจริงที่น่าสนใจเกี่ยวกับคำสั่ง switch (เปลี่ยน)
- นิพจน์ที่ใช้ใน switch จะต้องเป็นประเภทหนึ่ง (int, char และ enum) ไม่อนุญาตให้ใช้ประเภทอื่นในการแสดงออก
int main(){
float x = 1.1;
switch (x){
case 1.1: printf("Choice is 1");
break;
default: printf("Choice other than 1, 2 and 3");
break;
}
return 0;
}Output: Compiler Error: switch quantity not an integer
ใน Java อนุญาตให้ใช้สตริงได้ในสวิตช์ (ดูที่นี่)
2. ข้อความทั้งหมดที่ตามหลังตัวพิมพ์ที่ตรงกันดำเนินการจนกว่าจะถึงคำสั่ง break
int main(){
int x = 2;
switch (x){
case 1: printf("Choice is 1\n");
case 2: printf("Choice is 2\n");
case 3: printf("Choice is 3\n");
default: printf("Choice other than 1, 2 and 3\n");
}
return 0;
}Output:
Choice is 2
Choice is 3
Choice other than 1, 2 and 3
// There is no break in some cases (ไม่มีการหยุดพักในบางกรณี)#include <stdio.h>
int main(){
int x = 2;
switch (x){
case 1: printf("Choice is 1\n");
case 2: printf("Choice is 2\n");
case 3: printf("Choice is 3\n");
case 4: printf("Choice is 4\n");
break;
default: printf("Choice other than 1, 2, 3 and 4\n");
break;
}
printf("After Switch");
return 0;
}Output:
Choice is 2
Choice is 3
Choice is 4
After Switch
3. บล็อกเริ่มต้นสามารถวางได้ทุกที่ ตำแหน่งเริ่มต้นไม่สำคัญว่าจะยังคงดำเนินการหากไม่พบที่ตรงกัน
(บล็อกเริ่มต้นถูกวางไว้เหนือกรณีอื่นๆ)#include <stdio.h>
int main(){
int x = 4;
switch (x){
default: printf("Choice other than 1 and 2");
break;
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
}
return 0;
}Output: Choice other than 1 and 2
4. นิพจน์ที่สำคัญที่ใช้ใน ป้ายกำกับ จะต้องเป็นนิพจน์คงที่
// A program with variable expressions in labelsโปรแกรมที่มีนิพจน์ตัวแปรในป้ายกำกับ#include <stdio.h>
int main(){
int x = 2;
int arr[] = {1, 2, 3};
switch (x){
case arr[0]: printf("Choice 1\n");
case arr[1]: printf("Choice 2\n");
case arr[2]: printf("Choice 3\n");
}
return 0;
}
Output:Compiler Error: case label does not reduce to an integer constant
5. ข้อความที่เขียนไว้ด้านบนจะไม่ถูกดำเนินการหลังจากคำสั่งสวิตช์การควบคุมการถ่ายโอนไปยังกรณีที่ตรงกันคำสั่งที่เขียนก่อนกรณีจะไม่ถูกดำเนินการ
// Statements before all cases are never executed(คำชี้แจงก่อนทุกกรณีจะไม่ดำเนินการ)#include <stdio.h>
int main(){
int x = 1;
switch (x){
x = x + 1; // This statement is not executed (คำสั่งนี้ไม่ได้ถูกดำเนินการ)
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
default: printf("Choice other than 1 and 2");
break;
}
return 0;
}Output: Choice is 1
6. สองกรณีป้ายกำกับไม่สามารถมีค่าเดียวกัน
// Program where two case labels have same value(โปรแกรมที่สองกรณีป้ายกำกับมีค่าเท่ากัน)#include <stdio.h>
int main(){
int x = 1;
switch (x){
case 2: printf("Choice is 1");
break;
case 1+1: printf("Choice is 2");
break;
}
return 0;
}Output: Choice is 1