2013-08-29 109 views
1

C++中有以下可能嗎?開關語句繼續

switch (value) { 
    case 0: 
     // code statements 
     break; 
    case 1: 
    case 2: 
     // code statements for case 1 and case 2 
     /**insert statement other than break here 
     that makes the switch statement continue 
     evaluating case statements rather than 
     exit the switch**/ 
    case 2: 
     // code statements specific for case 2 
     break; 
} 

我想知道是否有辦法讓switch語句繼續評估其餘的案例,即使它遇到了匹配的案例。 (例如其他語言的continue聲明)

+4

爲什麼你有'案例2'兩次? – Barmar

+1

你是什麼意思*掃描*其餘案件? 'switch'就像一個'goto',只有當它到達'break'時纔會停止。 – andy256

+0

@ andy256我的意思是評估。 – Dan

回答

4

簡單的if怎麼樣?

switch (value) 
{ 
case 0: 
    // ... 
    break; 

case 1: 
case 2: 
    // common code 
    if (value == 2) 
    { 
     // code specific to "2" 
    } 
    break; 

case 3: 
    // ... 
} 
+4

如果公共代碼和特定代碼的順序無關緊要,您還可以執行'案例2:{/ *代碼特定於2 * /}案例1:{/ * common code * /}'。 –

+0

謝謝!我沒有想到這一點! – Dan

1

是的,只是不要休息。它自然會落在其他開關語句上。

+2

'case 1'結尾的下降:case 2:'labels會處理以下'value'爲'1'或'2'的語句。原來的問題似乎只是在'value'爲'2'而不是'1'時處理第二個case 2:'標籤。 –

2

確定案例標籤後,無法讓switch繼續搜索其他匹配標籤。您可以繼續處理下列標籤的代碼,但這並不能區分爲什麼達到標籤的不同原因。所以,不,沒有辦法限制選擇。實際上,在C++中禁止使用重複的case標籤。