If statement, compare one variable to multiple

后端 未结 6 1318
挽巷
挽巷 2021-01-22 10:53

Example:

int value = someValue;
if (value == (valueOne OR valueTwo OR valueThree)){
//do code
}

I would like to avoid re-typing value

6条回答
  •  粉色の甜心
    2021-01-22 11:24

    You use || to do boolean OR comparison. The single bar, | is used for bit operations. Your current syntax is incorrect.

    if(value ==1 || value==2 || value ==3)
    

    Of course, it might be better to do a range check here like so:

    if(value>=1 && value<=3)
    

    Not sure what you're trying to do though.

    If the OR comparison makes more sense for you here, you should define some constants for these values, or consider an enumerated type. The literals 1, 2, and 3 have no meaning to other developers.

提交回复
热议问题