问题
Working with legacy code I came across some strange variable assignments that I am not sure are legal VB6 syntax, but I cannot find the documentation to back up the feeling.
Dim ComStart, ComEnd, CR As Boolean
ComStart = ComEnd = CR = False
My suspicions are
a) the original declarations should be
Dim ComStart as Boolean, ComEnd as Boolean, CR as Boolean
b) the declarations as they are implemented now will not assign anything to ComStart
.
Any answers or documentation are much appreciated
回答1:
The code you have found is technically legal VB6, because it compiles and runs. But it is very likely that the original author thought the code would do something different! There are two misunderstandings.
ComStart
andComEnd
andCR
are variants, not Booleans.- In VB6
=
is the equality operator, not the assignment operator found in C.CR = False
does not change the value ofCR
. It compares the current value ofCR
toFalse
, and evaluates asTrue
ifCR
is equal toFalse
. Let's say it evaluates asFalse
- Now you have the expression
ComEnd = False
. Again, this does not change the value ofComEnd
. It compares it withFalse
, and evaluates asTrue
ifComEnd
is equal toFalse
. This time let's say it evaluates asTrue
. - Now you have the assignment statement
ComStart = True
. This sets the value ofComStart
toTrue
So your original code
Dim ComStart, ComEnd, CR As Boolean
ComStart = ComEnd = CR = False
Creates two variants ComStart
and ComEnd
and a Boolean CR
, and then
CR
keeps its default value,False
ComEnd
keeps its default value,Empty
ComStart
is set toFalse
becauseEmpty = (Empty = False)
isFalse
.
Simple! ... I hope the rest of the legacy code is less, well, accidental.
回答2:
So the code should be, as you guessed:
Dim ComStart as Boolean, ComEnd as Boolean, CR as Boolean
That's a common mistake on VB6 developers with little or no experience, or .NET developers working on VB6 code :). It works, because VB6 would assume the value assigned and would cast it automatically, but it can also cause nasty bugs really hard to debug.
来源:https://stackoverflow.com/questions/13012230/multiple-variable-assignments-in-one-statement-in-visual-basic-6