在同一个 if 测试中测试多个条件? [英] Test for multiple conditions in same if test?

查看:43
本文介绍了在同一个 if 测试中测试多个条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用谷歌搜索但失败了.

I tried googling and failed.

使用 C,我有一个 IF 语句.我想针对两个不连续的值测试一个变量.

Using C, I have an IF statement. I want to test a variable against two non-consecutive values.

可以吗

if (state == 1 || 3)

if (state == 1 || 3)

表示状态为 1 或状态为 3.

Meaning if state is 1 or if state is 3.

或者必须是

if (state == 1 || state == 3)

if (state == 1 || state == 3)

我认为第一个实际上意味着 state 是 1 还是 3,这意味着测试将始终为真(如果为真或为真).

I'm thinking the first actually means if state is 1, or 3, which means the test will always be true (if true or true).

不,我不想使用 case/switch 语句.我正在尝试少打字.

No, I don't want to use a case / switch statement. I'm trying to type less.

推荐答案

你必须使用长变体

if (state == 1 || 3)

评估总是为 true 因为它被解释为

evaluates always to true because it is interpreted as

if ((state == 1) || (3))

因为在评论中问到了 C++,一位 M.M 提到了运算符重载,一个 C++ 解决方案

Because for C++ was asked in the comments an M.M mentioned operator overloading, a C++ solution

#include <cstdlib>
struct State {
    struct Proxy {
        int v;
        bool res;
        Proxy(int v, bool res) : v(v), res(res) {}

        Proxy operator || (int a) const {
            return Proxy(v, res || (a == v));
        }

        operator bool() const { return res; }
    };
    int v;
    State(int v) : v(v) {}

    Proxy operator == (int a) {
        return Proxy(v, a == v);
    }
};


int main(int argc, char *argv[])
{
    State   state(atoi(argv[1]));

    if (state == 1 || 3 || 5)
        return 1;
    else
        return 0;
}

这篇关于在同一个 if 测试中测试多个条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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