An external variable located in a function?

According to wikipedia:

http://en.wikipedia.org/wiki/External_variable

An external variable can also be declared inside a function.

What is the purpose of the external variable declared inside the function? Should it also be static?

+6
source share
5 answers

The only difference between declaring an external variable in a namespace scope is:

extern int x; void foo() { cout << x; } 

and declare it in the function area:

 void foo() { extern int x; cout << x; } 

lies in the fact that in the latter case, x is visible only inside the function.

Everything you do extern declaration area even more.


Here's a similar example using namespaces:

In the namespace area:

 #include <string> using std::string; void foo() { string str1; } string str2; // OK 

In the area of ​​functions:

 #include <string> void foo() { using std::string; string str1; } string str2; // Error - `using` not performed at this scope 
+2
source

This allows you to restrict access to the global area within a certain area:

 int main() { extern int x; x = 42; //OKAY } void foo() { x = 42; //ERROR } int x; 
+4
source

An external declaration is part of the function. It just means that no other functions 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`. 

This is just a way to "isolate" a variable, so it is not accidentally used in places where it should not be used.

+1
source

The text refers to a non-defining declaration of an external function within the function. External definitions within functions are illegal.

Thus, a non-defining declaration of an external variable inside a function simply means that you want to use this variable inside this function. The variable itself must be a global variable defined elsewhere.

Basically, if you do not need access to this global variable (defined elsewhere) in the entire translation block and just need it inside this function, then it would be nice to declare it locally. Thus, you do not pollute the global namespace with identifiers that do not require other functions.

0
source

The extern key indicates that the identifier has an external binding. This means that it is associated with the same name in another place where it is declared with an external connection. That is, different instances of the name in different places refer to the same object.

Declaring an identifier inside a block (including a block defining a function) gives it the area of ​​the block. The scope of this instance of the identifier ends at the end of the block.

Combining extern with the block scope allows the function to see the external identifier without cluttering the namespace of other functions. (However, this is often bad practice.)

0
source

Source: https://habr.com/ru/post/946299/


All Articles