2012-08-16 49 views
3

如果您有一個switch語句,並且希望某個代碼在值爲一個值時運行另一個如何操作?下面的代碼總是進入默認情況。你如何有邏輯或在開關陳述的一部分?

#include <iostream> 
using namespace std; 

int main() 
{ 
    int x = 5; 
    switch(x) 
    { 
     case 5 || 2: 
      cout << "here I am" << endl; 
      break; 
     default: 
      cout << "no go" << endl; 
    } 

    return 0; 
} 

回答

8

像這樣:

switch (x) 
{ 
case 5: 
case 2: 
    cout << "here I am" << endl; 
    break; 
} 

被譽爲 「通過落」。

只是想指出的是,default情況下,在發佈代碼執行的原因是,5 || 2結果是1true)。如果您在發佈的代碼中將x設置爲1,則將執行5 || 2個案(請參閱http://ideone.com/zOI8Z)。

+0

爲什麼5 || 2評估爲2?這不符合邏輯或... – Celeritas 2012-08-16 21:54:44

+0

@Celeritas,我從來沒有說它評估爲'2',它是邏輯OR。 – hmjd 2012-08-16 21:55:55

+0

對不起,我的意思是5 || 2評估爲1.但在二進制101 OR 11 = 111這是7,而不是1.對嗎? – Celeritas 2012-08-16 22:04:53

3

switch落空

switch(x) 
{ 
    case 2: 
    case 5: 
     cout << "here I am" << endl; 
     break; 
    default: 
     cout << "no go" << endl; 
} 
7

讓它落空:

int main() 
{ 
    int x = 5; 
    switch(x) 
    { 
     case 5: 
     // there's no break statement here, 
     // so we fall through to 2 
     case 2: 
      cout << "here I am" << endl; 
      break; 
     default: 
      cout << "no go" << endl; 
    } 

    return 0; 
} 

5 || 2,順便說一句,結果爲1(或true,因爲它是一個邏輯表達式),你可以試試它。

1
case2: 
case5: 
    //do things 
    break;