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 identifiers):

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

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -

PostgreSQL 9.x - pg_read_binary_file & inserting files into bytea -