According to wikipedia:
http://en.wikipedia.org/wiki/External_variable
An external variable may also be declared inside a function.
What is the purpose of an extern variable being declared within a function? Would it have to be static too?
According to wikipedia:
http://en.wikipedia.org/wiki/External_variable
An external variable may also be declared inside a function.
What is the purpose of an extern variable being declared within a function? Would it have to be static too?
It allows for restricting access to a global to some scope:
int main()
{
extern int x;
x = 42; //OKAY
}
void foo()
{
x = 42; //ERROR
}
int x;
The external declaration goes inside a function. It simply means that no other functions can see the variable.
void func()
{
extern int foo;
foo ++;
}
void func2()
{
foo--; // ERROR: undeclared variable.
}
In another source file:
int foo; // Global variable. Used in the other source file,
// but only in `func`.
It is just a way to "isolate" a variable, so it doesn't accidentally get used in places where it isn't supposed to be used.
The only difference between declaring an external variable at namespace scope:
extern int x;
void foo() {
cout << x;
}
and declaring it at function scope:
void foo() {
extern int x;
cout << x;
}
is that in the latter case, x
is only visible inside the function.
All you're doing is further tightening the scope of the extern
declaration.
Here's an analogous example using namespaces:
At namespace scope:
#include <string>
using std::string;
void foo() {
string str1;
}
string str2; // OK
At function scope:
#include <string>
void foo() {
using std::string;
string str1;
}
string str2; // Error - `using` not performed at this scope
The text refers to a non-defining declaration of an extern variable inside function. Extern definitions inside functions are illegal.
So, a non-defining declaration of an extern variable inside function simply means that you want to use that variable inside that function. The variable itself must be a global variable defined elsewhere.
Basically, if you don't need access to that global variable (defined elsewhere) in the entire translation unit and just need it inside that function, it is perfectly good idea to declare it locally. That way you are not polluting global namespace with identifiers no other function needs.
The extern
keyword says that an identifier has external linkage. This means that it is linked to the same name anywhere else it is declared with external linkage. That is, the different instances of the name in different places refer to the same object.
Declaring an identifier inside a block (including the block that defines a function) gives it block scope. The scope of that instance of the identifier ends at the end of the block.
Combining extern
with block scope allows a function to see an external identifier without cluttering the name space of other functions. (Nonetheless, it is often bad practice.)