你如何有逻辑的或情况下的交换机统计的一部分? [英] How do you have logical or in case part of switch statment?

查看:119
本文介绍了你如何有逻辑的或情况下的交换机统计的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有一个switch语句,并希望某些代码在值为一个值时运行,那么如何执行呢?以下代码总是使用默认大小写。

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


推荐答案

>

Like this:

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

被称为掉落。

只要指出在发布代码中执行 default 情况的原因是 5 ||的结果。 2 1 true )。如果在发布的代码中将 x 设置为 1 ,则 5 || 2 案例(请参阅 http://ideone.com/zOI8Z )。

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).

这篇关于你如何有逻辑的或情况下的交换机统计的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆