c语言中for中声明变量,C中for循环中的变量重新声明

当尝试为多个平台编译以下(简化)代码时,我发现它在某些方面是失败的,即IBM的xlC_r.进一步的调查发现,它也没有进来和cl..它与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".

ang子错误:

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) {

^

来错误:

"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;

}

}

}

这显然会允许结束重新声明.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值