为什么这不是无限递归? VB.NET 中的默认变量初始化如何工作?

发布于 2024-08-29 07:52:17 字数 344 浏览 3 评论 0原文

我刚刚在代码中犯了一个有趣的错误:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

秋凉 2024-09-05 07:52:17

规范 指出:

在执行任何变量初始值设定项之前,所有变量都会初始化为其类型的默认值。

The spec says, that:

All variables are initialized to the default value of their type before any variable initializers are executed.

远昼 2024-09-05 07:52:17

该变量并非未初始化。

执行步骤 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 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.

放肆 2024-09-05 07:52:17

这里根本没有递归。读取变量永远不会导致递归。最坏的情况是,我可以看到编译器在尝试在初始化子句中使用变量时抛出错误,但显然它不会,或者在第一种情况下您将无法编译。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文