I saw in this post that we can uncover a global variable where a local variable of the same name is in scope by using extern
and a compound statement.
In that post, the example given is like
#include<stdio.h>
int a = 12;
int main(void)
{
int a = 15;
printf("Inside a's main local a = : %d\n", a);
{
extern int a;
printf("In a global a = %d\n", a);
}
return 0;
}
and the shadowed variable is a global variable.
But when I tried a program like
#include<stdio.h>
int main()
{
int i=5;
for(int i=0; i<2; ++i)
{
{
extern int i;
printf("\nGlobal: %d", i);
}
printf("\nLocal: %d", i);
}
}
it failed.
I tried making the outer i
static in case it works only if the outer variable is static but still it didn't work.
Can somebody tell me why the second program doesn't work? And how to get around it if it's possible?
Maybe this method works only if the outer variable is global?
Edit: The comments made me realize that the use of extern
will just make a global variable visible. But is there a way around this without changing variable name?