lol, that title of this thread is such a great pun XD
So I was working on some code today, and stumbled upon this:
Code:
If (Val(Parse(4)) Or Val(Parse(5)) Or Val(Parse(6))) < 1 Or (Val(Parse(4)) Or Val(Parse(5)) Or Val(Parse(6)) Or Val(Parse(7))) > 20 Then
And in another section, I found this:
Code:
If Str$(lblStrength.Caption) And Str$(lblDefense.Caption) And Str$(lblAgility.Caption) > 0 Then
And without naming names, I wanted to let the author of the code know that this is WRONG! This might be a common mistake among new programmers, so I decided to write a bit about it quick.
I know what the authors intentions are, in the first snippet he was thinking, "If parse 4, 5, or 6 are less than 1, or if 4, 5, 6, or 7 are larger than 20, then we have a problem..." (got that? XD)
The second snippet he was thinking, "If the value of all of these is larger than 0, we can continue"
I'm sure a few of you were rubbing your eyes as I was, but I'd bet even more of you think these both look fine.
To fully understand this, you need to understand that the keywords AND, OR, and NOT (and the rest...) are BOOLEAN OPERATORS and not logical operators. while they may seem like logical operators on boolean values (True/False) they can be used on numbers as well, and the results are potentially unexpected.
For example, if I have the number 5 AND 10
What is the result? 5 AND 10 = 0b0101 AND 0b1010 = 0b0000 = 0. Wow!
If I take 9 AND 10 = 0b1001 AND 0b1010 = 0b1000 = 8. Did you expect that?
5 OR 10 = 0b0101 OR 0b1010 = 0b1111 = 15
9 OR 10 = 0b1001 OR 0b1010 = 0b1011 = 11
The boolean operators AND, OR, and NOT operate on the BIT level, so to illustrate above I used the 0b prefix (which is a standard) to indicate my numbers in binary.
So you're best off staying away from using boolean operators on numbers unless you understand the examples I posted above, and are trying to achieve that effect.
"BUT LEA! THERES OTHER PLACES IN THIS CODE LIKE THIS! HERES ONE!"
Code:
If (n >= 65 And n <= 90) Or (n >= 97 And n <= 122) Or (n = 95) Or (n = 32) Or (n >= 48 And n <= 57) Then
Whats the difference here? The EXPRESSION n>=65 is a BOOLEAN value. It's either true or false. Therefore True and True = True. True And False = False. Then they're ORd and it completes a logical boolean expression.
Sorry, this stuff is hard to explain. Understand?