Metamorphing Machine I rather be this walking metamorphosis
than having that old formed opinion about everything!

WTF, VB6? Part 2

This is the second post in the WTF, VB6? series
The previous one can be found here.

VB6 has a feature called fixed-length strings. It is a string that always has the same length.
It is declared like this:

Dim LastName As String * 50

If you did not set the string above to anything, it is initialized with 50 null chars.
If you set it like this:

LastName = "Biasic"

Now it has 6 characters plus 44 spaces.
What if you set it like this?

LastName = "This is a very long and - quite frankly - unnecessary last name"

Our little string still has 50 characters ("This is a very long and - quite frankly - unnecess"). The exceeding ones were discarded.

It is pretty handy when you are dealing with a fixed-length field text file, for instance.
Or when you need to embed it in a structure.

But what we get when running the code below?

Sub Main()
Dim LastName As String * 50
LastName = "Biasic"
ShowMeThisStringsLength LastName
End Sub

Sub ShowMeThisStringsLength(ByRef s As String)
Debug.Print "This string's length is " & Len(s)
End Sub

We get "This string's length is 6".
WTF, VB6?!?

This happens because when passing any string as an argument to another procedure, it is converted from a fixed-length string to a variable-length one.

So what happens if we try this:

Sub Main()
Dim LastName As String * 50
LastName = "Biasic"
ChangeThisStringToMe LastName
Debug.Print "This string's length is " & Len(s)
End Sub

Sub ChangeThisStringToMe (ByRef s As String)
s = "No longer Biasic"
End Sub

We'll get 50 again. The string now contains "No longer Biasic".
VB6 does not guarantee fixed-length strings when passed to other procedures, but it goes to great lengths (pun intended) to ensure it when used locally.

Andrej Biasic
2020-04-22