Why isn't this infinite recursion? How does default variable initialization work in VB.NET?
I just made an interesting mistake in my code:
Dim endColumn As Integer = startColumn + endColumn - 1
The code was actually supposed to be:
Dim endColumn As Integer = startColumn + numColumns - 1
The interesting thing is, I would thi开发者_高级运维nk that this code should be recursive and loop indefinitely, as the initialization of endColumn sort of calls itself. However, it seems that the code just treats the uninitialized variable as a 0 and so I get startColumn + 0 - 1
. What is happening here behind the scenes? When does a variable get assigned a default value?
The spec says, that:
All variables are initialized to the default value of their type before any variable initializers are executed.
The variable isn't uninitialized.
Execution Step 1: Dim endColumn As Integer
The default value of an Integer
is 0 so endColumn = 0 at this point.
Execution Step 2: startColumn + endColumn - 1
Since endColumn = 0 from step 1, this is the value that is used.
There is no recursion at all here. Reading variables never causes recursion. At worst, I could see the compiler throwing an error in trying to use a variable in its initialization clause, but apparently it does not or you would not have been able to compile in the first case.
精彩评论