为什么这不是无限递归? VB.NET 中的默认变量初始化如何工作?
我刚刚在代码中犯了一个有趣的错误:
Dim endColumn As Integer = startColumn + endColumn - 1
代码实际上应该是:
Dim endColumn As Integer = startColumn + numColumns - 1
有趣的是,我认为这段代码应该是递归的并且无限循环,因为 endColumn 的初始化会调用自身。然而,代码似乎只是将未初始化的变量视为 0,因此我得到 startColumn + 0 - 1
。幕后发生了什么?什么时候为变量分配默认值?
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 think 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
规范 指出:
The spec says, that:
该变量并非未初始化。
执行步骤 1:
Dim endColumn As Integer
Integer
的默认值为 0,因此此时 endColumn = 0。执行步骤 2:
startColumn + endColumn - 1
由于步骤 1 中的 endColumn = 0,因此这是使用的值。The variable isn't uninitialized.
Execution Step 1:
Dim endColumn As Integer
The default value of anInteger
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.