c - 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 want access outer i
(int i=5
) value in printf
how can done?
the relevant part of c99 standard, section 6.2.1 (scopes of identiļ¬ers):
4 [...] if identifier designates 2 different entities in same name space, scopes might overlap. if so, scope of 1 entity (the inner scope) strict subset of scope of other entity (the outer scope). within inner scope, identifier designates entity declared in inner scope; entity declared in outer scope hidden (and not visible) within inner scope.
update
to prevent pmg's answer disappearing: can access outer block variable declaring pointer before hiding occurs:
int = 5; { int *p = &i; int = 7; printf("%d\n", *p); /* prints "5" */ }
of course giving hiding variables never needed , bad style.
Comments
Post a Comment