如果测试,测试相同的多个条件? [英] Test for multiple conditions in same if test?
问题描述
我尝试使用Google搜索并失败。
使用C,我有一个IF语句。我想针对两个非连续值测试变量。
是否可以做
if(state == 1 || 3)
含义如果state为1或state为3。 / p>
或者它必须是
if(state == 1 || state == 3)
我认为第一个实际意味着状态是1还是3,这意味着测试总是是真的(如果是真或真)。
有没有办法写这个而不必多次重写变量名?
不,我不想使用 case
/ switch
语句。我正在尝试少打字。
你必须使用长变种
if(state == 1 || 3)
总是评估 true
,因为它被解释为
if ((state == 1)||(3))
编辑:
因为在评论中提到了C ++,MM提到了运算符重载,C ++解决方案
#include< cstdlib>
struct State {
struct Proxy {
int v;
bool res;
代理(int v,bool res):v(v),res(res){}
代理运算符|| (int a)const {
return Proxy(v,res ||(a == v));
}
运算符bool()const {return res; }
};
int v;
State(int v):v(v){}
代理运算符==(int a){
return Proxy(v,a == v);
}
};
int main(int argc,char * argv [])
{
州州(atoi(argv [1]));
if(state == 1 || 3 || 5)
return 1;
其他
返回0;
}
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.
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;
}
这篇关于如果测试,测试相同的多个条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!