How do you have logical or in case part of switch statment?

你。 提交于 2019-12-30 10:29:14

问题


If you have a switch statement and want certain code to be run when the value is one value or another how do you do it? The following code always goes to the default case.

#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;
}

回答1:


Like this:

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

Known as "falling through".

Just to point out that the reason the default case is executed in the posted code is that the result of 5 || 2 is 1 (true). If you set x to 1 in the posted code the 5 || 2 case would be executed (see http://ideone.com/zOI8Z).




回答2:


Make it fall through:

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, by the way, evaluates to 1 (or true, as it is a logical expression), you can try it.




回答3:


Let the switch fall-through:

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



回答4:


case2:
case5:
   //do things
   break;



回答5:


Here is a really good read about switch/case and their slight difference between C/C++ and some other information about labels (ABCD:) you might like to know.



来源:https://stackoverflow.com/questions/11995568/how-do-you-have-logical-or-in-case-part-of-switch-statment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!