Reputation: 9393
I have some doubt on below code
#include<stdio.h>
int i=6;
int main()
{
int i=4;
{
extern int i;
printf("%d",i); //prints 6
}
printf("%d",i); //prints 4
}
we know that extern
keyword says compiler, the variable is somewhere outside. So the question is why the extern
keyword is accessing the global i
variable but not the i
variable which is within the main function? I was thinking there must be a contradiction because both variables are available to the inner braces as global variable. So does extern keyword access the variable which is outside the function or does it also access the variable which is outside the braces.
Upvotes: 2
Views: 3789
Reputation: 375
/* what Ed Heal said */ Yet, I think it would be best to illustrate it with additional example. I modified Your example to do a little more. The comments in the code tells the most of it:
#include <stdio.h>
int i = 6;
int main(void)
{
int i = 4;
printf("%d\n", i); /* prints 4 */
{
extern int i; /* this i is now "current". */
printf("%d\n", i); /* prints 6 */
{
int *x = &i; /* Save the address of the "old" i,
* before making a new one. */
int i = 32; /* one more i. Becomes the "current" i.*/
printf("%d\n", i); /* prints 32 */
printf("%d\n", *x); /* prints 6 - "old" i through a pointer.*/
}
/* The "previous" i goes out of scope.
* That extern one is "current" again. */
printf("%d\n", i); /* prints 6 again */
}
/* That extern i goes out of scope.
* The only remaining i is now "current". */
printf("%d\n", i); /* prints 4 again */
return 0;
}
Upvotes: 1
Reputation: 279405
extern
doesn't mean outside the current scope, it means an object with external linkage. An automatic variable never has external linkage, so your declaration extern int i
can't possibly refer to that. Hence it's hiding it, the same as the automatic variable hid the global.
Upvotes: 5
Reputation: 7144
I think you're asking whether you're right in thinking that the extern int i
declaration should cause the first printf
to resolve i
to 4
because that int i=4
statement is in a parent scope of the scope in which the extern is declared.
The answer is no, hence the behaviour you're seeing. An extern
declaration within a function is used to declare the existence of an external variable and won't ever resolve to a local variable (a variable declared within the function).
Upvotes: 1
Reputation: 3037
int i=4 is not global variable, if you try to access var i which is inside main in another function your compiler will thrown error about var i is undeclared. This code illustrates it.
void func() {
printf("i is %d\n",i);
}
main() {
int i=10;
func();
}
Whereas the i outside of main is global variable, which you can access in all functions.
Upvotes: 1
Reputation: 60037
Before the printf
that prints 6 you are asking the compiler to use the i
defined after the #include
. The closing brace then tells the compiler that the extern
is no longer in effect, therefore it uses the scope where i
is set to 4.
Upvotes: 3