Dim x, y As Boolean x = Not 23 > 14 y = Not 23 > 67 ' The preceding statements set x to False and y to True.
En el siguiente ejemplo se muestra cómo utilizar los operadores And, Or y Xor.
Dim a, b, c, d, e, f, g As Boolean a = 23 > 14 And 11 > 8 b = 14 > 23 And 11 > 8 ' The preceding statements set a to True and b to False. c = 23 > 14 Or 8 > 11 d = 23 > 67 Or 8 > 11 ' The preceding statements set c to True and d to False. e = 23 > 67 Xor 11 > 8 f = 23 > 14 Xor 11 > 8 g = 14 > 23 Xor 8 > 11 ' The preceding statements set e to True, f to False, and g to False.
Inconvenientes de las evaluaciones cortocircuitadas
En el ejemplo siguiente se muestra la diferencia entre And, Or y sus homólogos de evaluación cortocircuitada.
Dim amount As Integer = 12 Dim highestAllowed As Integer = 45 Dim grandTotal As Integer
If amount > highestAllowed And checkIfValid(amount) Then ' The preceding statement calls checkIfValid(). End If If amount > highestAllowed AndAlso checkIfValid(amount) Then ' The preceding statement does not call checkIfValid(). End If If amount < highestAllowed Or checkIfValid(amount) Then ' The preceding statement calls checkIfValid(). End If If amount < highestAllowed OrElse checkIfValid(amount) Then ' The preceding statement does not call checkIfValid(). End If
Function checkIfValid(ByVal checkValue As Integer) As Boolean If checkValue > 15 Then MsgBox(CStr(checkValue) & " is not a valid value.") ' The MsgBox warning is not displayed if the call to ' checkIfValid() is part of a short-circuited expression. Return False Else grandTotal += checkValue ' The grandTotal value is not updated if the call to ' checkIfValid() is part of a short-circuited expression. Return True End If End Function
Dim x As Integer x = 3 And 5
-
Los valores se tratan como binarios:
3 en formato binario = 011
5 en formato binario = 101
-
El operador And compara las representaciones binarias, una posición binaria (bit) a la vez. Si los dos bits en una posición dada son 1, entonces se coloca un 1 en esa posición del resultado. Si uno de los dos bits es 0, entonces se coloca un 0 en esa posición del resultado. En el ejemplo anterior, esto funciona como sigue:011 (3 en formato binario)
101 (5 en formato binario)
001 (el resultado, en formato binario)
-
El resultado se trata como decimal. El valor 001 es la representación binaria de 1, por lo que x = 1.
Los operadores AndAlso y OrElse no admiten las operaciones bit a bit.