for循环中计数器变量的范围是多少?

我在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 ++中,过去在for表达式中声明的变量的范围是在其后面的块的外部。 这在一段时间之前已经改变,因此在for表达式中声明的变量的范围是在其后面的块的内部。 C#遵循以后的方法。 但这与此无关。

这里发生的是C#不允许一个作用域隐藏外部作用域中具有相同名称的变量。

因此,在C ++中,这曾经是非法的。 现在这是合法的。

 for (int i; ; ) { } for (int i; ; ) { } 

同样的事情在C#中是合法的。 有三个范围,其中“i”未定义的外部,以及两个子范围,每个范围都声明自己的“i”。

但你正在做的是这样的:

 int i; for (int i; ; ) { } 

这里有两个范围。 一个外部声明一个’i’,一个内部也声明一个’i’。 这在C ++中是合法的 – 外部’i’是隐藏的 – 但它在C#中是非法的,无论内部范围是for循环,while循环还是其他。

试试这个:

 int i; while (true) { int i; } 

这是同样的问题。 C#不允许嵌套作用域中具有相同名称的变量。

for循环后,增量器不存在。

 for (int i = 0; i < 10; i++) { } int b = i; // this complains i doesn't exist int i = 0; // this complains i would change a child scope version because the for's {} is a child scope of current scope 

你不能在for循环之后重新声明i的原因是因为在IL中它实际上会在for循环之前声明它,因为声明发生在作用域的顶部。

是啊。 语法:新范围位于由curl字符串定义的块内。 function:在某些情况下,您可能需要检查循环变量的最终值(例如,如果中断)。

只是一些背景信息:序列没有进入它。 只有范围的想法 – 方法范围,然后是for循环的范围。 因此,“一旦循环终止”就不准确。

因此,您发布的内容与此相同:

 int i = 0; // scope error string str = ""; // no scope error for (int i = 0; i < 3; i++) { string str = ""; } 

我发现像这样思考它会使我的心理模型中的答案“更合适”。