首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

语句作用域的一个小疑点

2012-09-14 
语句作用域的一个小问题!#include iostream#include vectorusing namespace stdint main(){vectorin

语句作用域的一个小问题!
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> ivec;
int ival;
cout << "Enter numbers(Ctrl+Z to end):" << endl;
while (cin >> ival)
ivec.push_back(ival);
if (ivec.size() == 0)
{
cout << "No element?!" << endl;
return -1;
}
cout << "Sum of each pair of counterpart elements in the vector:"
<< endl;
vector<int>::size_type cnt = 0;
for (vector<int>::iterator first = ivec.begin(),
last = ivec.end() -1;first < last;++first,--last)
{
cout << *first + *last << "\t";
++cnt;
if (cnt%6 == 0)
cout << endl;
}
if (first == last)
cout << endl
<< "The center element is no been summed "
<< "and its value is "
<< *first << endl;
return 0;
}
这是C++ Primer第四版里的一个习题源代码(是书里的原答案),按书里讲first,last的作用域都是语句作用域,出了for循环就被释放内存了,VC++2010也确实报错。但是我在C++ Primer Plus第五版里看到的确是刚好相反,说for后面括号里定义的变量是全局变量。不知道谁对谁错,请高人指点!

[解决办法]
很早的时候,在 for 的 () 定义的变量在 for 后面是可见的。
后来这个规则修改了,这就是 for 的一致性。
在VC60 向高版本转换的时候,需要修改这个一致性,以兼容旧的项目。

而 for 的 {} 里面的变量在 for 后面是肯定不可见的。
这是 C++ 的 块作用域。
[解决办法]
有关for中变量作用域,各个编译器的实现是不一样的
简单的例子

C/C++ code
#include <stdio.h>int main(){  for(int i=1;i<10;i++)    ;  printf("%d\n",i);  } 

热点排行