- Home /
Right way to use multiple "or" withinin "if" statement?
Is this the correct way to use several "or" within a if statement?
private var someint
private var otherint
function Update{
if(someint == ((otherint+1)||(otherint+2)||(otherint+3))){
//do stuff
}
}
Im mostly not sure about if I am using parenthesis right in order to compare each of the 3 calculated ints separate from each other.
Answer by Huacanacha · Apr 11, 2015 at 04:36 AM
In C# this syntax will give a compile error because the conditional operators ( &&
and ||
) don't work with int
s. Unityscript/js compiles this because it's a less strongly typed language that allows implicit conversion of int to boolean, where any number not 0 or NaN means TRUE.
Consider your clause:
((otherint+1)||(otherint+2)||(otherint+3))
This will return the first non-zero number of the three. Then you compare someint
to it, meaning you are only comparing someint
one of your numbers (the first if otherint is not -1, the second otherwise). So for the most part your IF clause will be true if someint == otherint+1
.
Assuming you want to "do stuff" if someint
is equal to any of the three values do this:
if ((someint == otherint+1) || (someint == otherint+2) || (someint == otherint+3))
Or more efficiently in this case because you have a range of integral values:
if ((someint >= otherint+1) && (someint <= otherint+3))
Answer by maccabbe · Apr 11, 2015 at 04:20 AM
|| is mostly used to combine bools, i.e.
bool temp1;
bool temp2;
bool temp3=temp1||temp2;
In your case you would do something like
if((someint == otherint+1)||(someint==otherint+2)||(someint==otherint+3))){
//do stuff
}