Question

I've worked with VB6 for many years now but I bumped into something rather strange and I cannot confirm this result myself. So I'd like to know if the output of the following code is going to be

7

7

or

7

6

Here's the code:

Option Explicit

Private Sub cmdOk_Click()
Dim V As Integer
V = 6
Call AddV(V)
Print V

End Sub

Sub AddV(ByRef P As Integer)
P = P + 1
Print P

End Sub

On my system (Windows XP + VB6), this works as expected. So I get the first output. However, I've seen the same program on Windows 7 + VB6 and the output is not the same.

Can someone please explain why this is so? However, the same thing worked just fine on VB 2008 + Windows 7. I thought that call-by-value and call-by-reference were standard parameter passing techniques in any language/OS.

Thanks!

EDIT: cmdOK is a command button.

Was it helpful?

Solution

V = 6
Call AddV(V)

You are not going to observe this behavior with this code. Nor can this have anything to do with the Windows version, it isn't involved with VB6 code execution. There is however an easy explanation for your observation. Your code probably looked like this:

V = 6
AddV (V)

In other words, no Call keyword. Now something pretty horrible happens in VB6. The parentheses no longer mean the same thing anymore. You don't use parentheses to call a Sub, only when you call a Function. Instead, they become part of an expression, the same kind of parentheses you'd use when you'd write Print 4 * (5 + 6) for example. It produces a copy of the value of V. The called procedure updates that copy, it no longer affects the value of the V variable.

While this was intentional, the feature was a major bug factory and was not carried forward into VB.NET. Parentheses now always mean the same thing in a procedure call and you use them regardless of whether the called procedure is a Sub or a Function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top