Adam Beck
Adam Beck

Reputation: 1271

Comparing Integers Using "And" in If Statements

This may sound dumb but I am stuck and I am having no luck searching on the internet what would be causing this to happen. I have a method that I want to check to make sure that both integers entered are both positive:

    Public Function BothPositive(ByVal num1 As Integer, ByVal num2 As Integer) As Boolean
    If (num1 And num2) > 0 Then
        Return True
    Else
        Return False
    End If
End Function

Now if I were to enter some numbers in

  • BothPositive(1,1) = True
  • BothPositive(1,2) = False
  • BothPositive(-10, 10) = True

Why is this? What is going on with the order of operations in the comparison statement or what is the "And" trying to compare? I don't see why this wouldn't work.

EDIT: I understand how to work around but my question is why is this occuring? I want to know what is going on that is causing this.

Upvotes: 4

Views: 7504

Answers (3)

antlersoft
antlersoft

Reputation: 14786

And is a boolean operation, and won't work on integers the way you are expecting (it is doing a bitwise or). You have to write this as If num1 >0 And num2 > 0 Then...

Upvotes: 2

JaredPar
JaredPar

Reputation: 754763

In Vb.Net And represents a bitwise operator so what you're doing here is creating a value which is the bitwise AND of num1 and num2 and comparing that value to 0. What you want to do is compare each value individually against 0. try the following

If (num1 > 0) AndAlso (num2 > 0) Then

Note the use of AndAlso here instead of plain old And. The AndAlso is a boolean operator vs. a bitwise and is also short circuiting. You should almost always prefer it over And

Upvotes: 6

JClaspill
JClaspill

Reputation: 1745

Public Function BothPositive(ByVal num1 As Integer, ByVal num2 As Integer) As Boolean    
 If (num1 > 0 AND num2 > 0) Then
  Return True
 Else
  Return False
 End If
End Function

Upvotes: 1

Related Questions