代码之家  ›  专栏  ›  技术社区  ›  JohnB

for循环中计数器变量的作用域是什么?

  •  9
  • JohnB  · 技术社区  · 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 循环也一样。

    所以呢 对于 循环?

    说清楚点,我用的是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)
    
    4 回复  |  直到 16 年前
        1
  •  21
  •   Jeff Dege    16 年前

    我认为你们都混淆了C++和C语言。

    用C++表示,在表达式中声明的变量的范围是在它后面的块的外部。这一点在一段时间前已经改变了,因此for表达式中声明的变量的作用域是它后面的块的内部。C遵循后面的方法。但两者都与此无关。

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

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

    同样的事情在C#也是合法的。有三个作用域,外部作用域中没有定义“i”,还有两个子作用域,每个子作用域声明自己的“i”。

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

    这里,有两个范围。一个外在的表示“我”,一个内在的表示“我”。这在C++中是合法的,外部的“i”是隐藏的,但是它在C语言中是非法的,不管内部范围是for循环还是while循环,或者是什么。

    试试这个:

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

        2
  •  3
  •   Jimmy Hoffa    16 年前

    for循环后不存在incrementor。

    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
    

        3
  •  2
  •   Nicolas78    16 年前

    赞成。语法上:新范围在由卷曲字符串定义的块内。功能上:在某些情况下,您可能需要检查循环变量的最终值(例如,如果中断)。

        4
  •  2
  •   Kieren Johnstone    16 年前

    只是一些背景信息:序列不在其中。只不过是作用域的概念-方法作用域和 for 循环的范围。因此,“一旦循环终止”并不准确。

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

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

    我发现这样想会让答案更符合我的思维模式。。