开发者

How to access outer block variable in inner block when inner block have same variable declaration?

int mai开发者_运维百科n(int argc, char** argv) {
    int i=5;
    {
        int i=7;
        printf("%d\n", i);
    }
    return 0;
}

If I want to access outer i (int i=5) value in printf then how it can done?


The relevant part of the C99 standard, section 6.2.1 (Scopes of identifiers):

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.

Update

To prevent pmg's answer from disappearing: You can access the outer block variable by declaring a pointer to it before the hiding occurs:

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

Of course giving hiding variables like this is never needed and always bad style.


Store the outer i in another variable and then declare inner i. like-

int i = 5;
{
    int p = i;
    int i  = 7;
    printf("%d\n", p); /* prints "5" */
}


Rename the variable.


You cannot access it.


I can't see why you can't call one 'I' and one 'J'.

Different names for them would allow you to choose either.


Make a pointer to the old i before defining the new one. ( demo at http://ideone.com/dobQX )

But I like Jonathan's comment the best!


Short answer: you can't. It is hidden by the i in the inner-scope.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜