Click to See Complete Forum and Search --> : if statement behavior?


Sam
03-25-2004, 04:53 PM
In general, how would the following statement react:

if(var=="a"||var=="b"&&var2=="a"||var2=="b")
{
//action 1
}
else{
//action 2
}

would action 1 be triggered if var was equal to b and var 2 was equal to a? Or does it break apart the statement differently?

steelersfan88
03-25-2004, 05:22 PM
The operators are performed according to parentheses. Sometimes, these are left out. I know this is how it is for Visual Basic.

The conditions are evaluated. Then all the not's (Not or ! operator) are performed, switching the condition.

Then, all the and's (And or && operator) are performed, checking if they are both condition a and b (and c....). Finally, the Or's (Or or || operator) are performed.

Your example would then, in this case be evaluated as, imagining var = "a" and var2 = "b":

if(var=="a"||var=="b"&&var2=="a"||var2=="b")
if(true||false&&false||true)
if(true||false||true)
if(true)
[action1]

This is better settled with ()s for easier use,; this eems to be what is intended, to evaluate the left and right, and check if both true:

if((var=="a"||var=="b")&&(var2=="a"||var2=="b"))
if((true||false)&&(false||true))
if((true)||(true))
if(true)
[action1]

Sam
03-25-2004, 05:56 PM
ah, good 'ole parenthesis... knew it was something silly I was forgetting.

steelersfan88
03-25-2004, 06:08 PM
yea, luckily it wasn't the whole code that was messed up with a missing set of ()s, they get hard to keep track of and find!