【发布时间】:2011-03-26 12:03:16
【问题描述】:
我在 Visual Studio 2008 中收到以下错误:
Error 1 A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else
这是我的代码:
for (int i = 0; i < 3; i++)
{
string str = "";
}
int i = 0; // scope error
string str = ""; // no scope error
我知道一旦循环终止,str 将不复存在,但我也认为i 的范围也仅限于for 循环。
所以i 与在for 循环之外声明的变量具有相同的范围?
编辑:
为了清楚起见,我使用的是 C#。我正在讨论删除“C”标签。但是,由于正确答案解释了两者之间的区别,我认为留下两个标签是有意义的。
我在上面的代码注释中有一个错误:
for (int i = 0; i < 3; i++)
{
string str = "";
}
int i = 0; // scope error
string str = ""; // also scope error,
// because it's equivalent to declaring
// string str =""; before the for loop (see below)
【问题讨论】:
-
你已经标记了这个 c# 和 c。你问的是哪种语言?答案可能会有所不同,具体取决于您所指的语言。
-
请参阅stackoverflow.com/questions/2693138/… 了解相同的问题,Eric Lippert 给出了很好的回答。另见stackoverflow.com/questions/1196941/… 和stackoverflow.com/questions/2059210/…
-
为了清楚起见,标记
c#和c(或c++)没有问题,如果您开始使用 我在 C# 3.0 中收到以下错误(Visual Studio 2008)... 和更高版本 for-loop 范围的 C# 规则与 ANSI C 有何不同?,这似乎是您的本意。但是您没有在原始问题中的任何地方指定您使用的是什么语言,在这种情况下,大多数人都会查看标签......这就是两个语言标签的问题所在。