Using different logical operators in the same condition
The purpose of the following selection statement is to determine if a number falls between 100 and 1000 inclusive.
If sngNumber = 100 Or sngNumber > 100 And sngNumber = 1000 Or sngNumber < 1000 Then
lblAnswer.Text= "YES"
Else
lblAnswer.Text= "NO"
End If
Will it produce the desired result? To determine if the it will you must identify the pivotal value(s) and then test the logic with values that are less than, equal to, and greater than the pivotal value(s).
Does it do as intended? No
If not why?: The AND operator will be performed before the ORs resulting in “YES” for any number less than or equal to 1000, including all numbers less than 100
How could you alter this code to make it both correct and more readable?
If (sngNumber = 100 Or sngNumber > 100) And
(sngNumber = 1000 Or sngNumber < 1000) Then
lblAnswer.Text= "YES"
Else
lblAnswer.Text= "NO"
End If
Alternatively
If sngNumber >= 100 And
sngNumber < =1000 Then
lblAnswer.Text= "YES"
Else
lblAnswer.Text= "NO"
End If