加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

当内部块具有相同的变量声明时,如何访问内部块中的外部块变量?

发布时间:2020-12-16 10:42:48 所属栏目:百科 来源:网络整理
导读:int main(int argc,char** argv) { int i=5; { int i=7; printf("%dn",i); } return 0;} 如果我想访问printf中的外部i(int i = 5)值,那该怎么办呢? 解决方法 C99标准的相关部分,第6.2.1节(标识符的范围): 4 […] If an identifier designates two differe
int main(int argc,char** argv) {
    int i=5;
    {
        int i=7;
        printf("%dn",i);
    }
    return 0;
}

如果我想访问printf中的外部i(int i = 5)值,那该怎么办呢?

解决方法

C99标准的相关部分,第6.2.1节(标识符的范围):

4 […] If an identifier designates two different entities in the same name space,the scopes might overlap. If so,the scope of one entity (the inner scope) will be a strict subset of the scope of the other entity (the outer scope). Within the inner scope,the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope.

更新

要防止pmg’s answer消失:您可以通过在隐藏发生之前声明指向它的指针来访问外部块变量:

int i = 5;
{
    int *p = &i;
    int i  = 7;
    printf("%dn",*p); /* prints "5" */
}

当然,给出这样的隐藏变量是永远不需要的,而且总是很糟糕.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读