【问题标题】:Scope hiding in C范围隐藏在 C
【发布时间】:2012-01-19 15:18:33
【问题描述】:

C 有范围隐藏吗?

例如,如果我有一个全局变量:

int x = 3; 

我可以在函数或主“另一个”int x 中“声明”吗?

【问题讨论】:

    标签: c scope


    【解决方案1】:

    是的,这就是 C 的工作方式。例如:

    int x;
    
    void my_function(int x){ // this is another x, not the same one
    }
    
    void my_function2(){
      int x; //this is also another x
      {
        int x; // this is yet another x
      }
    }
    int main(){
      char x[5]; // another x, with a different type
    }
    

    【讨论】:

    • 如果主要不是 int (不同类型),例如 char array[5] x 怎么办?
    • 在这种情况下,类型无关紧要。如果您将x 声明为int,然后通过说您有一个char[5] 类型的新x,您将只能看到后者char x[5]
    【解决方案2】:

    是的,但有些编译器会抱怨或被告知抱怨。对于gcc,请使用-Wshadow

    【讨论】:

      【解决方案3】:

      是的,C 中存在范围隐藏。
      局部范围内的变量将在全局范围内隐藏相同的命名变量。

      【讨论】:

        【解决方案4】:

        是的。这是很有可能的。关于C中的各种作用域的详细解释请通过this帖子

        【讨论】:

          猜你喜欢
          • 2012-09-02
          • 1970-01-01
          • 2019-09-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-11
          • 1970-01-01
          • 2020-05-01
          相关资源
          最近更新 更多