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?
the extern keyword is used to extend the visibility of variables/functions. Since functions are visible throughout the program by default, the use of extern is not needed in function declarations or definitions. Its use is implicit. When extern is used with a variable, it's only declared, not defined.
just remember the concept that when we declare a variable as extern inside a function we can only define it outside of that function.
extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention. The extern "C" modifier may also be applied to multiple function declarations in a block. In a template declaration, extern specifies that the template has already been instantiated elsewhere.
External variables are also known as global variables. These variables are defined outside the function. These variables are available globally throughout the function execution. The value of global variables can be modified by the functions. “extern” keyword is used to declare and define the external variables.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With