Re:Regarding Block level Scope & Variable Life Time
Elankathir and everybody else,
Here's a sample:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim i As Short
For i = 1 To 10
Dim x As Short
x = 1
Next
Dim x As Short
MessageBox.Show("x = " & x)
End Sub
As shown, I get an error at the first declaration of x, saying that x hides
a variable declared in the enclosing block. This is interesting, since the
declaration is after the For loop. This appears to show that all
declarations happen before any code in a block is executed, regardless of
where the Dim statements are. Is that correct?
When I comment out the second declaration, I get an error in the message box
line saying that x is not accessible in this context because it is private.
It cannot be changed to protected or public.
I haven't tried it, but I'm pretty durn sure that in C++, a similar
construct would be perfectly acceptable. The inner x would be used in the
for loop, and the message box would show a random value because the outer x
would never have been initialized. There is no check for whether a variable
declaration in one scope hides a declaration in another scope. At most, a
warning, not an error, would have been generated.
I tried commenting out the inner declaration and leaving the outer
declaration. I got an error saying that x cannot be used before it is
declared.
Ah, well. This doesn't seem to be an issue I'm going to need to worry about
much in real life.
Rob
-