关于重新定义的小问题
为什么这是不允许的:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
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 ofa
is the block in the curly braces: a single iteration of the for loop.该代码执行两次。
但编译器只会读取“a”变量的定义一次。
The code is executed twice.
But the compiler will read the definition of the 'a' variable only once.
在第二种情况下,变量
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 newa
for every iteration. It is for instance not possible to assign a value toa
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.