gpt4 book ai didi

c++ - 在 C++ 中的 for 循环中重新声明变量

转载 作者:IT老高 更新时间:2023-10-28 22:29:28 37 4
gpt4 key购买 nike

当尝试为多个平台编译以下(简化的)代码时,我发现它在某些平台上失败了,即 IBM 的 xlC_r。进一步的调查发现,它在 comeau 和 clang 上也失败了。使用 g++ 和 Solaris 的 CC 编译成功。

代码如下:

int main()
{
int a1[1];
bool a2[1];

for (int *it = a1, *end = a1+1; it != end; ++it) {
//...
bool *jt = a2, *end = a2+1;
//...
}
}

xlC_r 错误:

"main.cpp", line 8.25: 1540-0400 (S) "end" has a conflicting declaration.
"main.cpp", line 6.25: 1540-0425 (I) "end" is defined on line 6 of "main.cpp".

clang 错误:

main.cpp:8:25: error: redefinition of 'end' with a different type
bool *jt = a2, *end = a2+1;
^
main.cpp:6:25: note: previous definition is here
for (int *it = a1, *end = a1+1; it != end; ++it) {
^

comeau 错误:

"ComeauTest.c", line 8: error: "end", declared in for-loop initialization, may not
be redeclared in this scope
bool *jt = a2, *end = a2+1;
^

问题是为什么这是一个错误?

查看 2003 年标准,它说以下 (6.5.3):

The for statement
for ( for-init-statement; condition; expression ) statement
is equivalent to
{
for-init-statement;
while ( condition ) {
statement;
expression;
}
}
except that names declared in the for-init-statement are in the same
declarative-region as those declared in condition

这里没有在条件中声明名称。

此外,它说 (6.5.1):

When the condition of a while statement is a declaration, the scope
of the variable that is declared extends from its point of declaration
(3.3.1) to the end of the while statement. A while statement of the form
while (T t = x) statement
is equivalent to
label:
{
T t = x;
if (t) {
statement;
goto label;
}
}

同样,我不确定这是否相关,因为条件中没有声明。因此,鉴于 6.5.3 的等效重写,我的代码应该与以下内容相同:

int main()
{
int a1[1];
bool a2[1];

{
int *it = a1, *end = a1+1;
while (it != end) {
//...
bool *jt = a2, *end = a2+1;
//...
++it;
}
}
}

这显然会允许重新声明 end。

最佳答案

标准有些模糊。您引用的代码等效于 while 循环意味着存在一个内部范围,循环内的声明可以隐藏条件中的声明;但是标准也说(引用 C++11,因为我手边没有 C++03):

6.4/2 The rules for conditions apply both to selection-statements and to the for and while statements

6.4/3 If the name is re-declared in the outermost block of a substatement controlled by the condition, the declaration that re-declares the name is ill-formed.

6.5.3/1 names declared in the for-init-statement are in the same declarative-region as those declared in the condition

它们之间的含义是不能重新声明名称。

该语言的较旧(1998 年之前)版本将 for-init-statement 中的声明放入循环外的声明区域。这意味着您的代码将是有效的,但这不会:

for (int i = ...; ...; ...) {...}
for (int i = ...; ...; ...) {...} // error: redeclaration of i

关于c++ - 在 C++ 中的 for 循环中重新声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12351460/

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