【发布时间】:2012-07-11 04:52:09
【问题描述】:
根据我对C++规范的理解(根据网上的标准草案),for循环可以改写为while循环和block用于初始化。根据我的理解,for-loop的迭代语句和body发生在同一个作用域,所以应该可以使用for-loop的body中声明的变量。 gcc 和 clang 都拒绝以下(人为的)代码,这是我真实代码的简化。
我显然可以通过在循环之外声明 j 来修复代码,但是为什么 j 超出了下面的范围?
int main()
{
for(int i=0; i<10; i=j) int j=i+1;
// // I must misunderstand the standard because I thought the above loop is
// // equivalent to the commented code below where j is clearly in scope.
// {
// int i=0;
// while(i<10) {
// int j=i+1;
// i=j;
// }
// }
return 0;
}
根据clang(和gcc),这是无效的。
test.cpp:3:26: error: use of undeclared identifier 'j'
for(int i=0; i<10; i=j) int j=i+1;
^
1 error generated.
【问题讨论】:
-
你在声明
j之后你在i=j中使用它...while循环不会这样做。 -
这是无效的语法,因为
j直到在for循环内才被声明,尽管在第一个循环完成之前它没有被使用。 -
@nhahtdh,这就是我的意思。编译器还没有看到声明。什么时候使用在这方面是无关紧要的。
-
@chris:我的评论比你晚一点,所以它会通知你。不过,它不是针对你的。
-
@nhahtdh,啊,我把它误认为是“二手”这个词的迂腐,但这是真的。
标签: c++ scope language-lawyer specifications