Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

int main(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?

like image 415
Anand Kumar Avatar asked Dec 01 '22 09:12

Anand Kumar


1 Answers

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.

like image 196
schot Avatar answered Dec 15 '22 06:12

schot