2012-08-16 44 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;