How does the Imp Logical Operator Work in VBA? - vba

I came across some code in VBA & I'm trying to understand how it works, but I've never encountered this operator.
What exactly does Imp operator do in VBA?
If (a <> 0 Imp b = 0) Then
MsgBox ("IMP Operator Result is : True")
Else
MsgBox ("IMP Operator Result is : False")
End If
Are there examples of when we would use it?
Obviously, this is not a bitwise comparison, but something else.

The documentation from the comment actually is not that good. This is what it says:
The Imp operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table.
If you take a look at the example:
You would see that the result is always True(or 1) in any possible cases but one. The single case, where the result is False (or 0) is when the first operand is True and the second operand is False.

Related

Why And operator in vb.net

I always use AndAlso while checking multiple conditions as it doesn't evaluate right side unless left one is true. I don't see any situation where someone would like to evaluate right side even if left one fails. If it was needed then why they didn't include same in C#.
Update:
As accepted answer pointed out that it exists because it is used for bitwise operation, that fine enough but I still think they would have overloaded And operator to serve both purposes and just not created AndAlso. If anyone can pour some light on it, this question is still open :)
They included the same in C#. In C# you can use & (And) or && (AndAlso).
There's no real use case i can imagine for the not short-circuit operator when comparing booleans, but And can be used with numeric values, and it then does a bitwise comparison. That's why it exists. But when comparing boolean types, you'll always be using the short-circuit version.
And is also a bit operator. Here is an example showing a mix of And an AndAlso.
Dim foo? As Integer = 5
If foo.HasValue AndAlso (foo And 1) = 1 AndAlso (foo And 4) = 4 Then
Stop
End If

VBA assignment statement with an OR clause

I've come across some code that looks something like this
If (condition) Then
array(index) = array(index) Or variable
End If
Being unfamiliar with VB, it looks to me like some kind of horrid result of a love affair between an assignment statement and a condition clause.
Functionally, I thought it looked like some kind of ?: ternary operation. I now assume it is, though certainly not in a form I'm used to.
I'm aware that the first branch will assign array(index) to itself, that's essentially how the code I'm working on works. I don't THINK it's relevant to the question, but it kinda weirds me out, and there is often more going on than what I realize with VB.
Not a duplicate of Is there a conditional ternary operator in VB.NET? since that question is asking if there IS one, rather than "what the heck does this mean"
What it's not.
There is no ternary operator in VBA. The closest you get is IIf, which evaluates both true and false expressions (so don't use it when either branch has side-effects!):
IIf({bool-expression}, {value-if-true}, {value-if-false})
So it's not anything like a ternary.
We don't know what's in array(index), but let's assume it's some Long:
array(index) = SomeLongInteger Or variable
What you're looking at is a regular assignment:
foo = 42 Or variable
The runtime is going to assign foo with a value. So first it must compute the right-hand side of the assignment (=) operator:
42 Or Variable
The Or operator is often used as a logical operator in Boolean expressions.
However the above expression isn't a Boolean expression, and the Or operator isn't a logical operator here.
What it is.
It's a bitwise operator (in VB the logical and bitwise operators are the same, which is indeed a bit (pun not intended) confusing). In the assignment foo = 42 Or Variable, foo will take the value of the bitwise comparison of 42 Or Variable.
Debug.Print 42 Or 12 'prints 46
How?
Think in binary. This is 42:
00101010
This is 12:
00001100
Then you bitwise-or the two values (remember your truth tables? True Or True = True; True Or False = True; False Or False = False) and you get this:
00101110
..which is the binary representation for - that's right - 46.
So, array(index) = array(index) Or variable does the following:
Read the value of array(index)
Read the value of variable
Bitwise-Or the two values
Assign the result of that operation back to array(index)

When does = perform comparison instead of assignment?

In VB.NET, there's no == operator for comparison, so the = operator serves that purpose as well as assignment. I have a function, and I want it to return the boolean result of a comparison, without storing that result in a variable:
Private Function foo() As Boolean
Dim bar As Integer = 1
Return bar = 2
End Function
Returns: False
OK, but what's the value of bar?
Private Function foo() As KeyValuePair(Of Boolean, Integer)
Dim bar As Integer = 1
Return New KeyValuePair(Of Boolean, Integer)(bar = 2, bar)
End Function
Returns: False, 1
It looks like = will perform a comparison when the statement context demands it, but is this guaranteed? That is, can I be sure that bar will never be set to 2 in this situation?
Also, I know that VB.NET doesn't allow chained inline assignments, which may be for the best. Does this odd = behavior cause any other quirks I should be aware of?
You cannot do in-line assignments in VB, Assignment is an explicit statement:
[Let] <<target-reference>> = <<value-expression>>
The Let is optional and implicit, and hardly ever used anymore. The general rule that you can use to distinguish the [Let] command from equality testing is that for Let, no other keyword may come before the target-reference in the statement. AFAIK, in all cases of = as equality testing, there is one or more other keywords that precede it in the statement.
In your first example, the keyword Return precedes your =, so it's an equality test, and not an assignment.
In your first example you can do either:
Return 2
or
bar = 2
Return bar
As for your question "OK, but what's the value of bar?", bar still equals one.
= in VB cause no quirks. It works exactly as documented, and it always has (including its predecessor, BASIC back to 1968).
If you are starting to code in VB (coming from a language like C#), you should start getting used to the peculiar VB way of doing things; which is based on the idea: as simple and intuitive for the programmer as possible. "If assignation and comparison happen always in different contexts, why not using the same operator and let the context define its exact meaning?" -> VB-way of seeing things. "No, different realities have to be accounted for by different operators. End of the discussion" -> C#-way. :)
Is this reliable? Can you blindly trust on these not-always-clear-for-a-programmer bits? Sure, VB.NET peculiarities are highly-reliable and trustworthy. You can always use = (or Is on some contexts, but VS would tell you) and be completely sure that the code will do what is expected. But the question is: are you sure that you write exactly what you want?
This last question is what, perhaps, is more criticable of VB and what might give some problems to programmers from other languages: the higher the flexibility, the more likely is that you make an error; mainly if you are used to a different format.
Regarding the chained inline assignments, I honestly don't see its true utility (and never use them in C#). Regarding other differences with respect to C#, there are plenty of them; in some cases, I think that the C# approach is better; other times, the VB.NET one. On readability/length of code, I can refer to the With Statement I have always found somehow useful which is not present in C#.
One way to have 100% sure that the expression will be evaluated as an boolean expression is to use ()
e.g
Dim a = 2
Return (a = 1)
Since you cannot set a value to a variable wihtin the parenthesis.
What i want to say is: on an return statament for example you cant assing a value to a variable so, even if you use
a = 1
The compilator knows that this expression only can be an boolean expression.
The same to the if statament and so on..
Heh back in QB45 days we used to exploit the fact that "True" was the numeric value -1. So you would see code like x = 1 - x * (x < 6) (translation: increment x, but reset to 1 when it gets to 6)

In how many languages is Null not equal to anything not even Null?

In how many languages is Null not equal to anything not even Null?
It's this way in SQL (as a logic language) because null means unknown/undefined.
However, in programming languages (like say, C++ or C#), a null pointer/reference is a specific value with a specific meaning -- nothing.
Two nothings are equivilent, but two unknowns are not. The confusion comes from the fact that the same name (null) is used for both concepts.
In VB6 the expression Null = Null will produce Null instead of True as you would expect.
This will cause a runtime error if you try to assign it to a Boolean, however if you use it
as the condition of "If ... Then" it will act like False. Moreover Null <> Null will also
produce Null, so:
In VB6 you could say that Null is neither equal to itself (or anything else), nor unequal!
You're supposed to test for it using the IsNull() function.
VB6 also has other special values:
Nothing for object references. Nothing = Nothing is a compile error. (you're supposed to compare it using "is")
Missing for optional parameters which haven't been given. It has no literal representation so you can't even write Missing = Missing. (the test is IsMissing(foo))
Empty for uninitialized variables. This one does test equal to itself although there's also a function IsEmpty().
... let me know if I've forgotten one
I remember being a bit disgusted with VB.
Oracle is this way.
SELECT * FROM dual WHERE NULL=null; --no rows returned
MySQL has a null-safe equality operator, <=>, which returns true if both sides are equal or both sides are null. See MySQL Docs.
In C#, Nullable<bool> has interesting properties with respect to logical operators, but the equality operator is the same as other types in that language (i.e., ((bool?)null == (bool?)null) == true).
To preserve the short-circuited behavior of the short-circuited logical operators, and to preserve consistency with the non-short-circuited logical operators, the nullable boolean has some interesting properties. For example: true || null == true. false && null == false, etc. This stands in direct contradiction with other three-valued logic languages such as ANSI SQL.
You can make ruby work that way:
class Null
def self.==(other);false;end
end
n=Null
print "Null equals nothing" if n!=Null
In SQL you would have to do something like:
WHERE column is NULL
rather than
WHERE column = NULL

Performance difference between IIf() and If

In Visual Basic, is there a performance difference when using the IIf function instead of the If statement?
VB has the following If statement which the question refers to, I think:
' Usage 1
Dim result = If(a > 5, "World", "Hello")
' Usage 2
Dim foo = If(result, "Alternative")
The first is basically C#'s ternary conditional operator and the second is its coalesce operator (return result unless it’s Nothing, in which case return "Alternative"). If has thus replaced IIf and the latter is obsolete.
Like in C#, VB's conditional If operator short-circuits, so you can now safely write the following, which is not possible using the IIf function:
Dim len = If(text Is Nothing, 0, text.Length)
IIf() runs both the true and false code. For simple things like numeric assignment, this isn't a big deal. But for code that requires any sort of processing, you're wasting cycles running the condition that doesn't match, and possibly causing side effects.
Code illustration:
Module Module1
Sub Main()
Dim test As Boolean = False
Dim result As String = IIf(test, Foo(), Bar())
End Sub
Public Function Foo() As String
Console.WriteLine("Foo!")
Return "Foo"
End Function
Public Function Bar() As String
Console.WriteLine("Bar!")
Return "Bar"
End Function
End Module
Outputs:
Foo!
Bar!
Also, another big issue with the IIf is that it will actually call any functions that are in the arguments [1], so if you have a situation like the following:
string results = IIf(Not oraData.IsDBNull(ndx), oraData.GetString(ndx), string.Empty)
It will actually throw an exception, which is not how most people think the function works the first time that they see it. This can also lead to some very hard to fix bugs in an application as well.
[1] IIf Function - http://msdn.microsoft.com/en-us/library/27ydhh0d(VS.71).aspx
According to this guy, IIf can take up to 6x as long as If/Then. YMMV.
Better use If instead of IIf to use the type inference mechanism correctly (Option Infer On)
In this example, Keywords is recognized as a string when I use If :
Dim Keywords = If(String.IsNullOrEmpty(SelectedKeywords), "N/A", SelectedKeywords)
Otherwise, it is recognized as an Object :
Dim Keywords = IIf(String.IsNullOrEmpty(SelectedKeywords), "N/A", SelectedKeywords)
On top of that, readability should probably be more highly preferred than performance in this case. Even if IIF was more efficient, it's just plain less readable to the target audience (I assume if you're working in Visual Basic, you want other programmers to be able to read your code easily, which is VB's biggest boon... and which is lost with concepts like IIF in my opinion).
Also, "IIF is a function, versus IF being part of the languages' syntax"... which implies to me that, indeed, If would be faster... if for nothing else than that the If statement can be boiled down directly to a small set of opcodes rather than having to go to another space in memory to perform the logic found in said function. It's a trite difference, perhaps, but worth noting.
I believe that the main difference between If and IIf is:
If(test [boolean], statement1, statement2)
it means that according to the test value either satement1 or statement2 will executed
(just one statement will execute)
Dim obj = IIF(test [boolean] , statement1, statement2)
it means that the both statements will execute but according to test value one of them will return a value to (obj).
so if one of the statements will throw an exception it will throw it in (IIf) anyway but in (If) it will throw it just in case the condition will return its value.
...as to why it can take as long as 6x, quoth the wiki:
Because IIf is a library function, it
will always require the overhead of a
function call, whereas a conditional
operator will more likely produce
inline code.
Essentially IIf is the equivalent of a ternary operator in C++/C#, so it gives you some nice 1 line if/else type statements if you'd like it to. You can also give it a function to evaluate if you desire.
Those functions are different! Perhaps you only need to use IF statement.
IIF will always be slower, because it will do both functions plus it will do standard IF statement.
If you are wondering why there is IIF function, maybe this will be explanation:
Sub main()
counter = 0
bln = True
s = iif(bln, f1, f2)
End Sub
Function f1 As String
counter = counter + 1
Return "YES"
End Function
Function f2 As String
counter = counter + 1
Return "NO"
End Function
So the counter will be 2 after this, but s will be "YES" only. I know this counter stuff is useless, but sometimes there are functions that you will need both to run, doesn't matter if IF is true or false, and just assign value from one of them to your variable.