c语言switch语句程序大全,C语言switch语句
C語言中的switch語句用于從多個條件執(zhí)行代碼。 就像if else-if語句一樣。
C語言中switch語句的語法如下:
switch(expression){ case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional ...... default: code to be executed if all cases are not matched; }
C語言中switch語句的規(guī)則如下 –
switch表達式必須是整數(shù)或字符類型。
case值必須是整數(shù)或字符常量。
case值只能在switch語句中使用。
switch case中的break語句不是必須的。這是一個可選項。 如果在switch case中沒有使用break語句,則匹配case值后將執(zhí)行所有后的語句。它被稱為通過C語言switch語句的狀態(tài)。
我們試著通過例子來理解它。假設(shè)有以下變量及賦值。
int x,y,z; char a,b; float f;
有效的Switch
無效的Switch
有效的Case
無效的Case
switch(x)
switch(f)
case 3;
case 2.5;
switch(x>y)
switch(x+2.5)
case ‘a(chǎn)’;
case x;
switch(a+b-2)
case 1+2;
case x+2;
switch(func(x,y))
case ‘x’>’y’;
case 1,2,3;
C語言中的switch語句的流程圖 –
我們來看一個簡單的C語言switch語句示例。創(chuàng)建一個源文件:switch-statment.c,其代碼如下 –
#include #include void main() { int number = 0; printf("Enter a number:"); scanf("%d", &number); switch (number) { case 10: printf("number is equals to 10n"); break; case 50: printf("number is equal to 50n"); break; case 100: printf("number is equal to 100n"); break; default: printf("number is not equal to 10, 50 or 100n"); } }
執(zhí)行上面示例代碼,得到以下結(jié)果 –
Enter a number:88 number is not equal to 10, 50 or 100
執(zhí)行第二次,結(jié)果如下 –
Enter a number:50 number is equal to 50 請按任意鍵繼續(xù). . .
switch語句直通到尾
在C語言中,switch語句是通過的,這意味著如果在switch case中不使用break語句,則匹配某個case之后的所有的case都將被執(zhí)行。
我們來試試通過下面的例子來了解switch語句的狀態(tài)。創(chuàng)建一個源文件:switch-fall-through.c,其代碼如下所示 –
#include #include void main() { int number = 0; printf("enter a number:"); scanf("%d", &number); switch (number) { case 10: printf("number is equals to 10n"); case 50: printf("number is equal to 50n"); case 100: printf("number is equal to 100n"); default: printf("number is not equal to 10, 50 or 100n"); } }
執(zhí)行上面示例代碼,得到以下結(jié)果 –
enter a number:10 number is equals to 10 number is equal to 50 number is equal to 100 number is not equal to 10, 50 or 100 請按任意鍵繼續(xù). . .
從上面的輸出結(jié)果中,可以清楚地看到,當(dāng)匹配 number = 10 之后,由于沒有break語句,其它后面的語句也打印執(zhí)行了。
¥ 我要打賞?? 糾錯/補充 收藏
總結(jié)
以上是生活随笔為你收集整理的c语言switch语句程序大全,C语言switch语句的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言作业集答案,C语言习题集及答案
- 下一篇: c语言剪刀石头布课程设计,C++剪刀石头