tags:

views:

117

answers:

6
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?

+2  A: 

You cannot access it.

GMan
A: 

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

Oli Charlesworth
+3  A: 

Rename the variable.

SLaks
+1  A: 

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

Different names for them would allow you to choose either.

Dave
+6  A: 

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.

schot
+1  A: 

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!

pmg