Multiple variable assignments in one statement in Visual Basic 6

自作多情 提交于 2020-02-22 15:29:12

问题


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 and ComEnd and CR are variants, not Booleans.
  • In VB6 = is the equality operator, not the assignment operator found in C.
    • CR = False does not change the value of CR. It compares the current value of CR to False, and evaluates as True if CR is equal to False. Let's say it evaluates as False
    • Now you have the expression ComEnd = False. Again, this does not change the value of ComEnd. It compares it with False, and evaluates as True if ComEnd is equal to False. This time let's say it evaluates as True.
    • Now you have the assignment statement ComStart = True. This sets the value of ComStart to True

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 to False because Empty = (Empty = False) is False.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!