【问题标题】:Refer to the variable outside block scope but inside function scope ( C/C++)在块范围外但在函数范围内引用变量(C/C++)
【发布时间】:2013-12-08 13:29:36
【问题描述】:

您好,我想知道如何在块内引用变量“x”(主函数的):

#include <stdio.h>
int x=10;  // Global variable x ---> let it be named x1.

int main()
{
  int x=5;     //  main variable x with function scope ---> let it be named x2.
  for(x=0;x<5;x++)
  {
     int x=2;      // variable x with block scope ---> let it be named x3.
     printf("%d\n",x);   // refers to x3
     printf("%d\n",::x); // refers to x1
     // What is the syntax to refer to x2??? how should I try to access x2?
  }
}

【问题讨论】:

    标签: c reference scope


    【解决方案1】:
    1. 对于 C

      您不能在 main 中访问 x1。局部变量的优先级高于全局变量。 主函数的 x 即 x2 可以在 for 块之外或之前访问。

    2. 对于 C++

      C++ 具有命名空间的特性,通过它你可以将特定的类/变量..等分组到一个范围内。

    因此,将第一个 x1 和 x2 包含在嵌套命名空间中(您甚至可以不使用它)。

    e.g.  namespace a { public : int x; namespace b { public : int x; }  }
    
       Then to use x1, a::x and to use x2 write a::b:: x;
    

    【讨论】:

      【解决方案2】:

      在这种情况下,您不能引用 x2。它是在本地范围内声明的(C 除了标签之外没有函数范围的概念),并且它的声明被内部块中的 x3 屏蔽。请参阅http://www-01.ibm.com/support/docview.wss?uid=swg27002103&aid=1 中第 3 页的“本地范围”。

      【讨论】:

        【解决方案3】:

        x2x3 是一样的。 for 块不是作用域。当编译器看到这个:

        int x = 5;
        
        for(x = 0; x < 5; x++) {
           int x = 2;
        }
        

        ...它实际上看到了这个:

        int x;
        x = 5;
        
        for(x = 0; x < 5; x++) {
           x = 2;
        }
        

        【讨论】:

        • 我们谈论的是 C 和 C++,而不是 JavaScript。这是错误的。
        • 这个答案是明确的、危险的、错误的。
        猜你喜欢
        • 2021-10-04
        • 1970-01-01
        • 2021-08-18
        • 2016-12-20
        • 2017-09-26
        • 1970-01-01
        • 1970-01-01
        • 2017-10-30
        • 2021-11-20
        相关资源
        最近更新 更多