Reputation: 315
In this code:
#include<stdio.h>
int var=100;
int main()
{
extern int var; //Declaration not Definition
printf("%d\n",var);
return 0;
}
100 is printed which is nothing out of the normal, but when declaration is removed from the main(), even then the global definition is being used. How is that happening? This has been taken from K&R which says:
The (global) variable must also be declared in each function that wants to access it.
Upvotes: 2
Views: 98
Reputation: 19
Another tip is if you want to use extern int var;
in another file, you can declare this piece of code in that file.
Upvotes: 1
Reputation: 6298
In:
#include<stdio.h>
int var=100;
int main(){...}
The var
has a global file scope. The main
does not need extern int var;
to know about it. extern int var;
would be important for other *.c
file to inform it that var
is defined somewhere else.
Note:
Use of global variable is usually considered bad practice precisely because of their non-locality: a global variable can potentially be modified from anywhere.
Global variables also make it difficult to integrate modules because software written by others may use the same global names unless names are reserved by agreement, or by naming convention.
Upvotes: 2
Reputation:
There is no need to include the extern keyword for variables which are declared in the same file or module. The global variable is visible to main
since it has global scope (i.e. it is visible to all functions within the file/module).
To clarify, using extern int x; tells the compiler that an object of type int called x exists somewhere. It's not the compilers job to know where it exists, it just needs to know the type and name so it knows how to use it. Once all of the source files have been compiled, the linker will resolve all of the references of x to the one definition that it finds in one of the compiled source files.
Upvotes: 4