2017-07-27 79 views
-2

我對開關語句並不熟悉。C - 開關語句 - 輸出差異

//S1 
switch(ch) { 
    case 'a': printf("eh? "); break; 
    case 'e': printf("eee "); break; 
    case 'i': printf("eye "); break; 
    case 'o': printf("ohh "); break; 
    case 'u': printf("you "); break; 
} 

//S2 
switch(ch) { 
    case 'a': printf("eh? "); 
    case 'e': printf("eee "); 
    case 'i': printf("eye "); 
    case 'o': printf("ohh "); 
    case 'u': printf("you "); 
} 

這兩個代碼塊之間的輸出是否有差異?你也可以解釋爲什麼嗎?

+7

請直接在你的問題中插入代碼,而不是圖像。 –

+0

[爲什麼C++要求在switch語句中斷?](https://stackoverflow.com/questions/29915854/why-does-c-require-breaks-in-switch-statements) –

+0

基本上,您問的是在C語言中,'break'運算符是什麼... –

回答

2

是的,有區別。

如果該switch相匹配的條件是在最上方的case語句,你不要在它的結束把break(或return)。它將通過(在statemet中執行它下面的所有語句)。

例如在開關:

switch(ch) { 
    case 'a': printf("eh? "); 
    case 'e': printf("eee "); 
    case 'i': printf("eye "); 
    case 'o': printf("ohh "); 
    case 'u': printf("you "); 
} 

如果ch是等於i,打印輸出將eye ohh you

1

如果switch case聲明沒有break,第一個匹配的case畢竟語句將被執行。 S2沒有任何break語句,因此,如果ch = a,S2將執行下面的所有語句,打印 eh? eee eye ohh you

0

是的,有區別。在你的第一個聲明:

switch(ch) { 
case 'a': printf("eh? "); break; 

它會打破這裏,只打印「呃?」。它不會執行第二個'e'部分。

在你的第二個聲明:

switch(ch) { 
    case 'a': printf("eh? "); 
    case 'e': printf("eee "); 
    case 'i': printf("eye "); 
    case 'o': printf("ohh "); 
    case 'u': printf("you "); 
} 

如果選擇的情況下「一」,因爲在這個聲明中沒有中斷,將執行「一」,之後每一個案件。它會打印出「呃呃呃呃你」。

如果您選擇案例'我',它會執行案例'我'和每一個案件後,打印「眼睛哦」你。

我還想再提一點,以'A'和'a'兩種情況。 你可以這樣做:

switch(ch) { 
    case 'a':case 'A': printf("eh? "); break; 
    case 'e':case 'E': printf("eee "); break; 
    case 'i':case 'I': printf("eye "); break; 
    case 'o':case 'O': printf("ohh "); break; 
    case 'u':case 'U': printf("you "); break; 
    default: break; 
}