For-Loop 计数器是否保留?
简单的问题。想象一下 ANSI-C 中的情况:
int i;
for(i=0 ; i<5 ; i++){
//Something...
}
printf("i is %d\n", i);
这会输出“i is 5”吗?
循环后,i
是否保留,或者 i
的值是否未定义?
Simple Question. Imagine this in ANSI-C:
int i;
for(i=0 ; i<5 ; i++){
//Something...
}
printf("i is %d\n", i);
Will this output "i is 5" ?
Is i
preserved or is the value of i
undefined after the loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的。如果 i 在 for 循环之外声明,则在循环退出后它仍保留在范围内。它保留循环退出时的任何值。
如果您在循环中声明 I:
则循环退出后 i 是未定义的。
Yes. If i is declared outside of the for loop it remains in scope after the loop exits. It retains whatever value it had at the point the loop exited.
If you declatred I in the loop:
Then i is undefined after the loop exit.
变量 i 是在循环范围之外定义的(这很好,否则在这种情况下您将无法打印它)。
并且它在循环的每一轮中都会进行后置调整,其结束条件是“当 i 大于或等于 5 时停止”。
所以此时 i 等于 5 确实非常有意义。
块作用域与 C 中的函数作用域并不完全相同。当您跳出循环作用域时,变量 i 不会神奇地“返回”到其先前的值。
Variable i is defined outside of the scope of the loop (which is great, or you wouldn't be able to print it in that case).
And it is post-icnremented for every-turn of the loop, for which the end condition is "stop when i is bigger or equal to 5".
So it really makes perfect sense for i to be equal to 5 at this point.
A block scope is not exactly the same as a function scope in C. The variable i doesn't "get back" magically to its previous value when you step out of the loop's scope.
循环后,
i
的值将为 5。除非你在里面做了类似的事情。
i
's value will be 5 after your loop. Unless you did something likeinside of it.
在我读过的大多数编码标准中,通常建议不要在退出循环后使用“i”。特别不要这样做:
虽然这可以工作,但编码很差。与替代方案相比,它的可读性和可维护性较差。例如
It's also generally recommended against using "i" after you exit the loop in most coding standards I have ever read. In particular do NOT do:
While this will work it is poor coding. It is less readable and maintainable than the alternatives. E.g.
是的,变量仅在声明它们的块内有效。
这是一个例子:
这是编译器:
Yes, variables are valid only inside the block in which they are declared.
Here's an example:
That's the compiler: