Anand Kumar
Anand Kumar

Reputation: 499

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

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?

Upvotes: 4

Views: 2309

Answers (7)

Renjith PR
Renjith PR

Reputation: 41

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" */
}

Upvotes: 4

schot
schot

Reputation: 11268

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.

Upvotes: 9

pmg
pmg

Reputation: 108978

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!

Upvotes: 1

Dave
Dave

Reputation: 7025

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

Different names for them would allow you to choose either.

Upvotes: 1

SLaks
SLaks

Reputation: 887797

Rename the variable.

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272667

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

Upvotes: 0

GManNickG
GManNickG

Reputation: 504103

You cannot access it.

Upvotes: 2

Related Questions