A variable declared in a loop stores a value through each iteration of the loop

I could not work if it is a bug or function

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 declaring a line inside a loop would not save its value, but after running this code, the console has 5 lines of "test value". If instead I declare strTest as:

 Dim strTest As String= "" 

Then the line does not save its value - so I would expect the function to work in the first place.

Is this intentional behavior a compiler?

+7
for-loop
source share
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 dependent on the whole procedure. If you enter a block more than once during a procedure, each variable in the block saves the previous value. To avoid unexpected results in this case, it is reasonable to initialize the block variables at the beginning of the block.

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

+6
source share

This is a well-defined behavior. From section 10.9, the VB 11 specification :

Each time a loop body is entered, a new copy of all local variables declared in this body, initialized with the previous values ​​of the variables, is created. Any reference to a variable inside the loop body will use the most recently created copy.

Note that the fact that it is a “fresh copy” is potentially important if you use any lambda expressions that commit a local variable. Later in the same section:

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

(Here is an example that clarifies this.)

+4
source share

All Articles