?
本文檔使用 php中文網(wǎng)手冊 發(fā)布
根據(jù)整數(shù)參數(shù)的值執(zhí)行代碼。
用于需要根據(jù)整數(shù)值執(zhí)行許多代碼分支中的一個或多個分支的情況。
開關(guān)(表達式)語句 |
---|
表達 | - | 整數(shù)類型的任何表達式(char,signed或unsigned integer或枚舉) |
---|---|---|
聲明 | - | 任何陳述(通常是復(fù)合陳述)。情況:和默認值:標簽允許在聲明中,并打破; 聲明有特殊的含義。 |
case constant_expression:語句 | (1) | |
---|---|---|
默認:語句 | (2) |
constant_expression | - | 任何整數(shù)常量表達式 |
---|
case:
只要所有constant_expressions的值都是唯一的(在轉(zhuǎn)換為提升的表達式類型之后),switch語句的主體可以具有任意數(shù)量的標簽。最多default:
只能有一個標簽(盡管嵌套的開關(guān)語句可能使用自己的default:
標簽,或者case:
標簽的常數(shù)與封閉開關(guān)中使用的常數(shù)相同)。
如果在轉(zhuǎn)換為提升的表達式類型后,表達式求值為等于constant_expressions之一的值,那么控制權(quán)將轉(zhuǎn)移到標有該constant_expression的語句。
如果表達式計算出的值與任何case:
標簽都不匹配,并且default:
標簽存在,則控件將轉(zhuǎn)移到標簽標簽所對應(yīng)的語句中default:
。
如果表達式求值的值與任何case:
標簽都不匹配,且default:
標簽不存在,則不會執(zhí)行任何開關(guān)主體。
break語句在遇到語句中的任何地方時會退出switch語句:
switch(1) { case 1 : puts("1"); // prints "1", case 2 : puts("2"); // then prints "2" ("fall-through")}
switch(1) { case 1 : puts("1"); // prints "1" break; // and exits the switch case 2 : puts("2"); break;}
與所有其他選擇和迭代語句一樣,switch語句建立塊范圍:表達式中引入的任何標識符在語句后超出范圍。如果一個VLA或其他具有不同修改類型的標識符在其范圍內(nèi)有一個case或者default標簽,則整個switch語句必須在其范圍內(nèi)(換句話說,VLA必須在整個交換機之前或之后最后一個標簽):switch(expr){int i = 4; //不是VLA; 可以在這里聲明f(i); //永遠不會調(diào)用// int ai; //錯誤:這里不能聲明VLA案例0:i = 17; 默認:; int ai; //可以在這里聲明VLA printf(“%d \ n”,i); //如果expr == 0則打印17,否則打印不確定的值} | (自C99以來) |
---|
switch
, case
, default
.
#include <stdio.h> void func(int x){ printf("func(%d): ", x); switch(x) { case 1: printf("case 1, "); case 2: printf("case 2, "); case 3: printf("case 3.\n"); break; case 4: printf("case 4, "); case 5: printf("case 5, "); default: printf("default.\n"); }} int main(void){ for(int i = 1; i < 10; ++i) func(i);}
輸出:
func(1): case 1, case 2, case 3.func(2): case 2, case 3.func(3): case 3.func(4): case 4, case 5, default.func(5): case 5, default.func(6): default.func(7): default.func(8): default.func(9): default.
C11標準(ISO / IEC 9899:2011):
6.8.4.2 switch語句(p:149-150)
C99標準(ISO / IEC 9899:1999):
6.8.4.2 switch語句(p:134-135)
C89 / C90標準(ISO / IEC 9899:1990):
3.6.4.2 switch語句