[英]Why same variable declaration for two FOR loops is right?
for(int i = 0 ; i<n ; i++) { do something }
具有等效的while循环:
int i = 0;
while(i<n) {
do something
i++;
}
现在,
for(int i = 4 ; false ; );
print i;//prints 4
for(int i = 7 ; false ; );
print i;//prints 7
根据我的理解,必须等于:
int i = 4;
while(false);
int i = 7;
while(false);
这是“ i”的两次声明。 而且,明显的错误。
现在,为什么在for循环中'i'没有重新声明错误?
代码在给出两个警告后运行:
警告:“ i1”的名称查找已更改为新的ANSI“ for”作用域
警告:在“ i1”处使用过时的绑定
不,他们不平等
for(int i = 4 ; false ; ); // scope of i is within for
print i; // This is a compilation error
for(int i = 7 ; false ; ); // scope of i is within for loop
print i; // This is a compilation error
在这里
int i = 4; // scope is not strictly blocked hence
while(false);
int i = 7; // re declaration error for this
while(false);
Microsoft对他们的编译器进行了扩展,如果启用了扩展,则for
循环变量的范围将扩展到外部范围,并且该示例将无法编译。 这不再是符合标准的,是历史遗物。 扩展名可以在项目设置中禁用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.