在语句的控制结构中定义的变量,仅在定义它们的块语句结束前有效。这种变量的作用域限制在语句体内。通常,语句体本身就是一个块语句,其中也可能包含了其他的块。一个在控制结构里引入的名字是该语句的局部变量,其作用域局限在语句内部。
// index is visible only within the for statement
for (vector<int>::size_type index = 0;
index != vec.size(); ++index)
{ // new scope, nested within the scope of this for statement
int square = 0;
if (index % 2) // ok: index is in scope
square = index * index;
vec[index] = square;
}
if (index != vec.size()) // error: index is not visible here
// index is visible only within the for statement
for (vector<int>::size_type index = 0;
index != vec.size(); ++index)
{ // new scope, nested within the scope of this for statement
int square = 0;
if (index % 2) // ok: index is in scope
square = index * index;
vec[index] = square;
}
if (index != vec.size()) // error: index is not visible here
真的是这样么?
for(int i=0;i<2;++i);
cout<<i;
为什么在vc6中写如下这段代码,程序能够编译通过并正确获取数值?
同问,为什么在while条件表达式里定义的变量外部却不可以访问?
while(int i = 1)
break;
cout<<i;
程序会报错。
解释:
for的问题是由于vc6对这个标准支持不够导致的,while是正常的。