Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable declared within a loop maintains value through each iteration of the loop

I couldn't work out if this is a bug or a feature

For i = 0 To 4
    Dim strTest As String
    If i = 0 Then
        strTest = "test value"
    End If
    Console.WriteLine(strTest)
Next

I thought that by declaring the string inside the loop, it wouldn't maintain its value but after running this code the console has 5 lines of "test value". If instead i declare strTest like:

Dim strTest As String= ""

Then the string doesn't maintain its value- which is how i would have expected the function to operate in the first place.

Is this intentional behavior by the compiler?

like image 912
5uperdan Avatar asked Sep 27 '13 10:09

5uperdan


2 Answers

"Broken as designed"

http://msdn.microsoft.com/en-us/library/1t0wsc67.aspx

Note Even if the scope of a variable is limited to a block, its lifetime is still that of the entire procedure. If you enter the block more than once during the procedure, each block variable retains its previous value. To avoid unexpected results in such a case, it is wise to initialize block variables at the beginning of the block.

The "block" here is the body if the FOR loop, and you are entering it one pr. iteration of the loop. And so strTest will retain the value set in the first iteration ("test value") for the next iterations (1, 2, 3, 4).

like image 59
Anders Johansen Avatar answered Oct 12 '22 23:10

Anders Johansen


It's well specified behaviour. From section 10.9 of the VB 11 specification:

Each time a loop body is entered, a fresh copy is made of all local variables declared in that body, initialized to the previous values of the variables. Any reference to a variable within the loop body will use the most recently made copy.

Note that the fact that it's a "fresh copy" is potentially important if any lambda expressions are used which capture the local variable. From later in the same section:

And when a lambda is created, it remembers whichever copy of a variable was current at the time it was created.

(There's an example which clarifies that.)

like image 31
Jon Skeet Avatar answered Oct 13 '22 00:10

Jon Skeet