Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An extern variable located in a function?

Tags:

c++

extern

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?

like image 258
user997112 Avatar asked Jun 01 '13 00:06

user997112


People also ask

Can extern be used inside a function?

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.

Can we define extern variable inside main?

just remember the concept that when we declare a variable as extern inside a function we can only define it outside of that function.

What is a extern function in C?

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.

What is meant by extern variable?

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.


2 Answers

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;
like image 148
Luchian Grigore Avatar answered Oct 17 '22 05:10

Luchian Grigore


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.

like image 21
Mats Petersson Avatar answered Oct 17 '22 06:10

Mats Petersson