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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With