gpt4 book ai didi

c++ - C++中for循环迭代语句期间范围内的变量

转载 作者:搜寻专家 更新时间:2023-10-31 01:14:22 25 4
gpt4 key购买 nike

根据我对C++规范的理解(根据在线标准草案),for循环可以改写为while循环和初始化 block 。按照我的理解,for循环的迭代语句和循环体发生在同一个作用域内,所以应该可以使用for循环体中声明的变量。 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.

最佳答案

for(int i=0; i<10; i=j) int j=i+1;

如果它是有效的语法,将与

相同
for(int i=0; i<10; i=j) 
{
int j=i+1;
}

for 循环然后访问 {} 范围内的“j”,该范围在执行第一个循环之前不存在。 C++ 是一种静态语言,它依赖于编译器能够在编译时解析其变量,但您正在做的是试图让它在运行时解析变量。

关于c++ - C++中for循环迭代语句期间范围内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11425755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com