C++:for 循环的范围?
#include <iostream>
using namespace std;
int main() {
int i;
for(i=0; i <= 11; i+=3)
cout << i;
cout << endl << i << endl;
}
输出为:0 3 6 和 9,一旦退出循环,输出为 12。 循环内和循环外 i 的地址看起来相同
我需要知道的是: for 循环内的 i 与 for 循环外初始化的 i 是否相同,因为变量 i 在 for 循环 i 之前首先初始化曾经被创造过吗?
#include <iostream>
using namespace std;
int main() {
int i;
for(i=0; i <= 11; i+=3)
cout << i;
cout << endl << i << endl;
}
output is: 0 3 6 and 9 and then once it exits the loop its 12.
The addresses of i inside the loop and out appear the same
What I need to know is: Is the i inside the for loop the same as the i that was initialized outside the for loop because the variable i was first initialized before the for loops i was ever created?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,循环内的 i 与循环外的 i 相同,因为您只声明了一次。
如果出于某种原因你希望它不同(我强烈建议你不要这样做,你应该为不同的变量选择不同的名称),你可以在 for 循环中重新声明 i :
Yes, the i inside the loop is the same as the i outside of the loop because you've only declared it once.
If for some reason you want it to be different (which I highly recommend against, you should choose different names for different variables) you could redeclare the i in the for loop:
这是相同的 'i' var
i is 12
::i is 0
It's de same 'i' var
i is 12
::i is 0
为了在 C++(以及 C)中创建新对象(变量),您必须显式定义它。在您的程序中,您有且只有一个变量定义 -
int i;
。这立即意味着那里只有一个变量i
。无论“for 循环的范围”或其他什么,都不会有任何其他i
的机会。In order to create a new object (variable) in C++ (as well as in C) you have to explicitly define it. In your program you have one and only one variable definition -
int i;
. That immediately means that there's one and only one variablei
there. There's no chance for any otheri
, regardless of any "scopes of for loop" or anything else.只有一个“i”变量。您只是在 foo 循环中分配一个值。
There is only one 'i' variable. You're just assigning a value in the foor loop.
这里只有一个变量 - 是的,循环内的 i 与退出循环后输出的 i 相同。然而,该变量仅作为循环的一部分进行初始化,而不是之前。
There is only one variable extant here - and yes, the i inside the loop is the same as the one you output after exiting the loop. However the variable was only initialized as part of the loop, not before.
形式的
for-loop
完全等同于:
因此,对于您的代码:
您现在能告诉我吗? Andrey 说得最好:如果你没有定义它,它就会不存在。
A
for-loop
of the form:Is exactly equivalent to:
So with your code:
Can you tell now? Andrey puts it best: if you didn't define it, it doesn't exist.