关于重新定义的小问题

发布于 2024-08-30 06:01:40 字数 231 浏览 2 评论 0原文

为什么这是不允许的:

int a = 0;
int a = 0;

但这是:

for (int i = 0; i < 2; ++i)
{
    int a = 0;
}

据我所知,for 循环内的代码将被执行两次,而实际上不会超出其范围,因此定义两次也应该是一个错误。
期待您的答复
谢谢。

Why this isn't allowed:

int a = 0;
int a = 0;

but this is:

for (int i = 0; i < 2; ++i)
{
    int a = 0;
}

As far as I know code inside for loop will be executed twice whitout actually going out of its scope, so it should also be an error to define a twice.
Looking forward to your answers
Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

面如桃花 2024-09-06 06:01:40

for 循环内只有一个定义。该变量被创建、使用,然后在右大括号处被销毁,并在下一个循环迭代中重新创建。定义了一个变量。

这在某种程度上类似于函数中定义的变量。函数可以被调用多次,但变量是一次。事实上,对于函数来说,函数可以被递归调用,并且会有多个变量处于活动状态,但是对于函数的每次执行,都会定义一个变量。

编辑:请注意,正如 @xtofl 正确指出的那样, i 的生命周期是整个 for 循环,而 a 的生命周期是大括号中的块: for 循环的单次迭代。

There is a single definition within the for loop. The variable gets created, used, then destroyed at the closing curly brace and recreated in the next loop iteration. There is a single variable defined.

This is somehow similar to a variable defined in a function. The function can be called many times, but the variable is one. In fact with functions, the function can be called recursively and there will be more than one variable alive, but for each execution of the function there is a single variable defined.

EDIT: Note, as @xtofl correctly points out, that the lifetime of i is the entire for loop, while the lifetime of a is the block in the curly braces: a single iteration of the for loop.

南城追梦 2024-09-06 06:01:40

该代码执行两次。
但编译器只会读取“a”变量的定义一次。

The code is executed twice.
But the compiler will read the definition of the 'a' variable only once.

雨的味道风的声音 2024-09-06 06:01:40

在第二种情况下,变量 a 的作用域仅在 for 循环内。您无法从外部访问它。并且它将再次为循环的每次迭代创建 - 就像每次迭代都会获得一个新的 a 一样。例如,不可能在一次迭代中为 a 分配一个值,并在以后的任何迭代中访问该分配的值。

您应该阅读变量作用域来获取有关此主题的更多信息。因为它在编程中非常重要。

In your second case the variable a is only scoped within the for-loop. You can not access it from outside. And it will be created for every iteration of your loop again - it is like you get a new a for every iteration. It is for instance not possible to assign a value to a in one interation and to access this assigned value in any later iteration.

You should read about variable scopes to get more information about this topic. since it is really important in programming.

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