我在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
(或c ++
)没有问题。但是,在原始问题的任何地方都没有指定您使用的语言,在这种情况下,大多数人会查看标签...这就是两个语言标签的问题所在。 - Ben Voigt