Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

c - Test for multiple conditions in same if test?

I tried googling and failed.

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

Is it possible to do

if (state == 1 || 3)

Meaning if state is 1 or if state is 3.

Or does it have to be

if (state == 1 || state == 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).

Is there a way to write this without having to rewrite the variable name multiple times?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you have to use the long variant

if (state == 1 || 3)

evaluates always to true because it is interpreted as

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

EDIT:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...