变量有效值范围的问题
C++ Primer上有这样一段:
在语句的控制结构中定义的变量,仅在定义它们的块语句结束前有效。这种变量的作用域限制在语句体内。通常,语句体本身就是一个块语句,其中也可能包含了其他的块。一个在控制结构里引入的名字是该语句的局部变量,其作用域局限在语句内部。
// 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
但是我自己在vc6里写了这样一段:
for(int i=0;i<2;++i);
cout<<i;
却可以正确编译及运行,为什么?为什么在for的语句块外也可以访问i?
而在while的条件表达式里定义的i却不能在句块外部访问?
while(int i = 1)
break;
cout<<i;
这样写程序会报错。