访问全局变量,局部隐藏 [英] Accessing global variable hidden by local

查看:135
本文介绍了访问全局变量,局部隐藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/618769/how-can-i-access-a-shadowed-global-variable-in-c\">How我可以在C访问阴影全局变量?


如何访问全局变量在C中,如果存在具有相同名称的本地变量?

  INT M = 20;
     无效的主要()
     {
       INT M = 30;
     }


解决方案

在C,你可以。当然,这只是小事,你不应该这样做在现实生活中。

声明的东西的extern 可以在任何地方进行,而且总是声明的变量链接到全球这个名字的。

 的#include&LT;&stdio.h中GT;INT I = 3;INT主(INT ARGC,字符** argv的){
    INT I = 6;    的printf(%d个\\ N,I);
    {//需要引入一个新的作用域
        EXTERN INT I; //阴影在这里允许的。        的printf(%d个\\ N,I);
    }
    返回0;
}

在C ++中,全球始终作为 ::我

Possible Duplicate:
How can I access a shadowed global variable in C?

how to access global variable in C , if there is local variable with same name?

     int m=20 ;  
     void main()  
     {  
       int m=30;  
     }   

解决方案

In C, you can. Of course this is just trivia, you should never do so in real life.

Declaring something extern can be done anywhere, and always links the declared variable to the global of that name.

#include <stdio.h>

int i = 3;

int main( int argc, char **argv ) {
    int i = 6;

    printf( "%d\n", i );
    { // need to introduce a new scope
        extern int i; // shadowing is allowed here.

        printf( "%d\n", i );
    }
    return 0;
}

In C++, the global is always available as ::i.

这篇关于访问全局变量,局部隐藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆