Go Down

Topic: Boolean Operators..&& (AND) is working but ! (NOT) is'nt working (Read 619 times) previous topic - next topic

nathanas

Dec 02, 2012, 03:26 am Last Edit: Dec 02, 2012, 03:30 am by nathanas Reason: 1
Hi there,
I'm trying to use NOT but unfortunately even with the codes below, arduino never gets into the second if.
Code: [Select]
if((readString.indexOf("test") >0) && (readString.indexOf("test2") >0))
{
  //1  
}//checks for test words

 if((!readString.indexOf("test") >0) && (!readString.indexOf("test2") >0))
{  
  //2  
 }  //check if there aren't any test words


No1 is working like a charm but No2 isn't for some reason.
When I check for 1, I type "test" and "test2", but when I check for 2 I type other words. It never gets into 2.
Can anyone explain to me why this is happening?


PaulS

You are applying the not to the wrong thing. What you want it !(readString.indexOf("test") >0).

Although, I think that is atrocious code. It's much better to change the value that readString.indexOf() is being compared to, in my opinion.

drone


Code: [Select]

 if((!readString.indexOf("test") >0) && (!readString.indexOf("test2") >0))



See the operator precedence: http://en.cppreference.com/w/cpp/language/operator_precedence

Note that ! is a higher precedence than >.

Consider what happens when we parenthesize by precedence:

Code: [Select]

if( !(readString.indexOf("test")) >0 && !(readString.indexOf("test2")) >0 )


PaulS is right too:
Code: [Select]
readString.indexOf("test")) <= 0
is a much more readable test and faster to type.

nathanas


Go Up