Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 668
Adam Beck Avatar asked Jan 20 '23 06:01

Adam Beck


1 Answers

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

like image 94
JaredPar Avatar answered Jan 30 '23 22:01

JaredPar