为什么在嵌套的FOR循环中使用相同的计数变量名称工作? [英] Why does using the same count variable name in nested FOR loops work?

查看:551
本文介绍了为什么在嵌套的FOR循环中使用相同的计数变量名称工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码不会出错?

Why does the following not give an error?

for (int i=0; i<10; ++i) // outer loop
{
    for (int i=0; i<10;++i) // inner loop
    {
    //...do something
    }
//...do something else
}

我理解的方式,大括号中的变量({...})只在这些大括号内的范围。但是内循环在外循环的括号内。所以,一旦我为内循环声明 int i = 0 ,我不应该得到关于多个定义的错误?

The way I understand it, variables in braces ({...}) are in scope only within these braces. But the inner loop is inside the braces of the outer loop. So as soon as I declare int i=0 for the inner loop, shouldn't I get an error about multiple definitions?

推荐答案

你实际上是创建一个与另一个变量同名的新变量。由于它们在不同的作用域中,这是允许的,内部作用域中的变量拥有该名称。您将无法访问内部作用域内的范围外的 i

You are actually making a new variable with the same name as another variable. Since they are in different scopes this is allowed, and the variable in the inner scope "owns" the name. You will not be able to access the outer-scoped i inside the inner scope.

for循环声明是for循环的范围的一部分,因此在第二个 i 的情况下作为内部范围的一部分。

The for loop declaration itself is part of the scope of the for loop, so counts as part of the inner-scope in the case of the second i.

这篇关于为什么在嵌套的FOR循环中使用相同的计数变量名称工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆