C language global variable and local variable problem and solution summary _c language

Source: Internet
Author: User
1, can local variables and global variable duplicate?
A: Yes, the local will screen the overall situation. To use a global variable, you need to use the "::"
Local variables can have the same name as global variables, and when referenced within a function, local variables with the same name are used instead of global variables. For some compilers, multiple local variables with the same name can be defined within the same function, such as defining a local variable with the same name in two loops, and the scope of that local variable within that loop.
2. How do I refer to a global variable that has already been defined?
Answer: extern
You can use the reference header file in a way that you can also use the extern keyword, if you use a reference header file to refer to a global change that is declared in the header file, and if you write that error, the error occurs during compilation, and if you use an extern reference, suppose you make the same mistake, There will be no error during compilation and an error during the connection.
3, the global variable can be defined in multiple. C file included in the header file? Why?
A: You can declare a global variable of the same name in a different C file in static form.
A global variable with the same name can be declared in a different C file, provided there is only one C file in which an initial value is assigned to the variable, and the connection is not faulted
4. What is the difference between a static global variable and a normal global variable? What is the difference between a static local variable and a normal local variable? What is the difference between a static function and a normal function?
The description of the global variable (external variable) before being labeled static constitutes a static global variable. The global variable itself is the static storage mode, static global variables are of course also static storage mode. The two are not different in the way they are stored. The difference between the two is that the scope of the Non-static global variable is the entire source program, and when a source program consists of multiple source files, non-static Global variables are valid in each source file. A static global variable restricts its scope, that is, it is only valid within the source file that defines the variable, and it cannot be used in other source files of the same source program. Because the scope of a static global variable is limited to one source file, it can only be common to functions within that source file, so it is possible to avoid causing errors in other source files.

From the above analysis, we can see that the change of the local variable to the static variable is the change of its storage mode that changes its lifetime. Changing the global variable to a static variable changes its scope and limits its use.

The static function differs from the normal function scope, only in this file. Functions that are used only in the current source file should be described as internal functions (static), and internal functions should be described and defined in the current source file. For functions that can be used outside the current source file, you should indicate in a header file that the source file to use these functions contains this header file
What is the difference between a static global variable and a normal global variable: Static global variables are only first made once, preventing them from being referenced in other file cells;
What is the difference between a static local variable and a normal local variable: the static local variable is only initialized once, and the next time it is based on the previous result value;
What is the difference between a static function and a normal function: There is only one copy of the static function in memory, and the normal function maintains a copy of each call.
5, the program's local variables exist in (stack), global variables exist in the (static area), and dynamic request data exists in the (heap).
Variables can be described in three places in a program: Inside a function, in the parameter definition of a function, or outside of all functions. Depending on the location defined, the variable can be divided into local variables, formal parameters and whole variables. From the space point of view, the variables can be divided into global variables and local variables, and from the point of view of time can have static storage variables and dynamic storage variables.
one, global variables and local variables
1. Local Variables
He refers to a function defined within a function as a variable scoped to define a local variable, which means that he can only use it in a function that defines him.
The most notable is that only when the program is executed to the module that defines it can it be generated, and the variable disappears once the module is executed.
Copy Code code as follows:

Func ()
{
int x; The scope of the local variable x is clear
......
}

2. Global variables
Always valid in the course of program execution
Copy Code code as follows:

int x=1;
Func ()
{
x=x+1;
}
Func1 ()
{
X=x-1;
}
Main ()
{
}

It is not difficult to see the scope of integer x
For global variables, if you do not initialize at the time of definition, the system automatically assigns a value of 0 characters to null '/0 '
The drawbacks of global variables increase memory overhead and reduce the generality of functions
The ideal place to define a global variable is at the beginning of the file when the function and some functions in other source program files in the same program need to use the global variable, use extern for that variable inside the function to explain that he's external.
(There will be a detailed explanation here)
Copy Code code as follows:

Main ()
{
extern int a,b;
printf ("Min is%d/n", min (a,b));
}
int a=1,b=2;
int min (x,y)
int x,y;
{
int z;
z=x<y?x:y;
return (z);
}

I also want to explain that the description of the external variable and the definition of the global variable are not the same thing.
The description of an external variable is simply to declare that the variable is a global variable that is defined externally and that the definition of a global variable is the
a global variable can only be defined once, but may be referenced more than once
In the same source file, when global and local variables have the same name, global variables do not work within the scope of local variables.
second, static storage variables and dynamic storage variables
Dynamic storage variables for variables that temporarily dynamically allocate storage space as needed during program execution
Variables that permanently occupy fixed memory during the program's operation are called static storage variables
Also explain that the program's instruction code is stored in the program code area of the static storage variable is stored in the static data area, including global variables and dynamic storage variables in the program stored in dynamic data areas such as function parameters and function call return address, etc.
variable storage category designation in C language
Auto
Auto is called an automatic variable, and if the function does not make other instructions, it is an automatic variable.
Static
Static is referred to as statically variable. According to the type of the variable can be divided into static local variables and static whole variables.
1. Static local Variables
It differs from a local variable in that the variable always exists when the function exits, but cannot be used by other functions, and the last result is saved when the function is entered again. Others are the same as local variables.
2. Static whole variable
Turbo C2.0 allows large programs to be compiled separately into separate module files, and then the target files of all modules are connected together, thus increasing the speed of compilation and facilitating the management and maintenance of the software. A static whole variable is one that is visible only in the source file where it is defined, but not in other source files. It is different from the whole variable: The whole variable can be described as an external variable (extern), used by other source files, and static variables can no longer be described as external, that is, only the source file used.
extern
extern is called an external variable. In order for a variable to be used in addition to the source file in which it is defined, it is also used by other files. Therefore, you must notify each program module file of the whole variable, which can be explained by extern.
Copy Code code as follows:

Document 1 is file1.c
int I, j;/* defines the whole variable * *

char c;
void func1 (int k);

Main ()
{
Func1 (20);/* Call Function/*
Func2 ();
.
.
.
}
func1 (int k) * User-defined function * *
{
j=k*100;
}
Document 2 is file2.c
extern int I, j;/* description will I, j Copy from File 1.
extern char C; /* copy C.
FUNC2 ()/* user-defined function * *
{
Static float k;/* defines a stationary variable * *
i=j*5/100;
k=i/1.5;
.
.
.
}

For the above two files file1.c and file2.c, compile with the integrated development environment of Turbo C2.0
When connecting, you should first create a. prj file. For example FILE.PRJ, the document reads as follows:
file1.c
File2.c
The File.prj file name is then written to the project name item in the Master menu project. and use F9.
When compiling a connection, you can produce an executable file named Fioe.exe.
Register
A register is called a register variable. It can only be used for integer and character variables. The variables described in the definition register are stored in the CPU registers by the turbo C2.0, rather than stored in memory like ordinary variables, which can increase the speed of the operation. But Turbo C2.0 only allows two register variables to be defined at the same time, once more than two, the compiler automatically treats the register variables that exceed the limit number as non register variables. Therefore, register variables are often used where the same variable name occurs frequently.
In addition, register variables only apply to local variables and function of formal parameters, it belongs to the auto type variable,
Therefore, it cannot be used as a whole variable. The definition of an integer register variable can be written as:
register int A;
The variable types and variable storage types described above will be gradually deepened through the definition and use of routine procedures in later learning.
1. Memory area of the program
Not all variables are knowable at all times. Some variables are visible throughout the program, and they are called global variables. Some variables can only be known in one function, called local variables. To understand these properties of a variable, you should first figure out the distribution area in the program's storage, as shown in Figure 5-2.
Figure 5-2 The area of the program in storage
A program divides the memory blocks that the operating system assigns to its operation into 4 regions:
(1) Code area, the code that holds the program, that is, each function code block in the program.
(2) Global data area, which holds the program's global data and static data.
(3) Heap area, storing the dynamic data of the program.
(4) Stack area, storing the local data of the program, namely the data in each function.
2. Global variables
Variables that are accessed outside the function are considered global variables and are visible in every function of the program. Global variables are stored in the global data area of memory. Global variables are established by the compiler and are initialized to 0, except when a global variable is defined specifically for initialization.
For example, the following code defines and uses a global variable. :
Copy Code code as follows:

int n=5;//global variable
void Main ()
{
int m=n;
//...
}
void Func ()
{
int s;
N=s;
...
}

n is defined outside of any function. N is initialized to 5, and C + + initializes it to 0 if N is not initialized when it is defined. The main () function uses the variable n1, and the function func () modifies the variable N. All two functions have access to the same memory area. A global variable that is defined in this way. is visible in all functions. If a function modifies N, then all other functions will see the modified variable.
Global variables begin to exist before main function main () is run. So you can access n variables in the main function. Global variables are usually defined at the top of the program. Once a global variable is defined, it is known anywhere in the program. You can define global variables anywhere in the middle of the program, but outside any function. All the function definitions before the global variable definition will not know the variable. For example:
Copy Code code as follows:

void Main ()
{
int m=n;//error:n no definition
...
}
int n;//global variable
void Func ()
{
int s=3;
N=s;
...
}

The global variable n in the code cannot be accessed by the main function main (). Compiling the code will cause the M initialization statement in main () to report an "n undefined" error.
3. Local variables
Variables defined within a function are visible only within that function. In addition, the type modification of a local variable is auto, which means that the variable allocates space in the stack, but it is customary to omit auto. For example:
Copy Code code as follows:

void Main ()
{
int n;//equivalent to Auto intn;
...
}
void Func ()
{
int n;
...
}

Both functions in your code contain a variable definition statement. Variables defined within a function are local to the function. There is also a variable n in the main () function in the N,func () function, but they are two different variables.
A function can define any name for a local variable without having to worry about the same name being used by other functions. This feature and the existence of local variables make C + + suitable for programming projects that are joined by multiple programmers. The project administrator assigns the programmer the task of writing a function and provides the program with parameters and expected return values. The programmer then proceeded to write the function without knowing the other parts of the program and the names of the variables used by other programmers in the project.
The local variables in the function are stored in the stack area. When the function starts to run, the local variable is allocated space in the stack area, and the local variable disappears when the function exits.
Local variables are not initialized. If the local variable is not explicitly initialized, its contents are unpredictable. For example:
Copy Code code as follows:

//*********************
* * Ch5_1.cpp * *
//*********************
#include <iostream.h>
int func1 ();
int Func2 ();
void Main ()
{
Func1 ();
cout <<func2 () <<endl;
}
int func1 ()
{
int n=12345;
return n;
}
int Func2 ()
{
int m;
return m; warning:possible use of ' m ' before definition
}

The results of the operation are:
12345
The main function, main (), successively calls the function func1 () and Func2 (), which are functions that have no parameters and return integers.
In Func1 (), the local variable n is defined and initialized to 12345. In Func2 (), the local variable m is defined and is not initialized. However, when the value of the variable is returned, the value is output in the main function, but it is found to be 12345, which is exactly the value initialized in the FUNCL () function. This means that, in Func2 (), the local variable m,c++, which is not explicitly initialized, is not initialized by default, and its value remains as the value of the original memory location. So why does the original memory location happen to hold a value of 12345? See the next section, "Function call mechanism."
Points:
1. Global variables:
(1) Define outside the function
(2) Visible globally
(3) generally defined at the top of the program
(4) stored in the memory of the global data area
(5) If not initialized at the time of definition, the value is 0
(6) If a function modifies N, then all other functions will see the modified variable
2. Local Variables:
(1) defining within a function
(2) visible only within the function
(3) stored in the stack area, when the function exits, the local variable disappears
(4) Different functions can use the same variable name
(5) If the local variable is not explicitly initialized, its contents are not predictable
Local Variables
Local variables are also called internal variables. A local variable is defined within a function. Its scope is limited to the inside of the function, it is illegal to leave the function and then use the variable.
Local variables can be stored in a dynamic (auto) storage type and a static (static) storage type.
The local variables of the dynamic storage type are dynamically allocated storage space, and the data is stored in the dynamic storage area (stack). When a function call is finished, it is automatically released, and the lifetime is the function execution procedure that declares the variable.
The local variable of the static storage type is the static allocation storage space, and the data is stored in the static storage area. During the entire operation of the program is not released, the lifetime throughout the process of running the program.
The local variables in the function, such as not specifically declared as static storage category, by default are dynamically allocated storage space, we usually declare the process of the variable auto is omitted by default.
Global Variables
A global variable, also called an external variable, is defined outside the function, and its scope starts at the variable definition and ends at the end of the program file. The global variables are all stored in the static store, and the global variables are allocated to the store when the program starts executing, and the program is released when the line is finished. In the process of program execution, they occupy a fixed storage unit, but do not dynamically allocate and release;
If the external variable is not defined at the beginning of the file, its valid scope is limited to the end of the file at the definition.
If the function before the definition point wants to refer to the external variable, you should use the keyword extern to declare the variable as an external variable before referencing it. Indicates that the variable is an external variable that has already been defined. With this declaration, you can legitimately use the external variable from the declaration. Its effective scope is extended to the end of the file from this file extern declaration.
If you precede the global variable declaration with the keyword static, then other files will no longer be able to access and use the variable, and the valid scope is limited to the end of the file at the definition.
can local variables be duplicate of global variables
Local variables can have the same name as global variables, but local variables mask global variables. When referencing this variable within a function, local variables with the same name are used, and global variables are not used.
PS: This is the same for extern declared global variables
---------------------------------------------------------------
General global variables are stored in the data area, local variables are stored in the stack area,
Dynamic variables are stored in the heap area, and the function code is placed in the code area.
---------------------------------------------------------------
Stack area is a common stack data structure, following the rules of LIFO LIFO, local variables are arranged there is ASM, so you can balance the stack at the end of a function, simple operation, high efficiency
The heap (dynamic area) should be called the stack (not to mix with the heap in the data structure) is a block generated by the program at compile time used to generate dynamic memory allocation, it is troublesome to operate the stack, and to judge the optimal address when assigning (to prevent unwanted memory fragmentation ( The efficiency of allocating and retrieving is much lower than that of stacks because of repeated new and delete clips in two pieces of memory (not easily allocated) in use.
---------------------------------------------------------------
The stack is the system provides the function, the characteristic is the fast high efficiency, the shortcoming is has the limitation, the data is inflexible, but the stack is the function library provides the function, the characteristic is nimble convenient, the data adapts the surface to be wide, but the efficiency > has certain reduction. The stack is the system data structure, is unique to the process/thread, the heap is the function library internal data structure, not necessarily unique. Memory for different heap allocations cannot interoperate with each other. Stack space is divided into two kinds, static allocation and dynamic allocation. Static allocations are done by the compiler, such as automatic variable (auto) allocations. Dynamic allocation is done by the Alloca function. The dynamic allocation of stacks does not need to be freed (is automatic) and there is no release function. For portable > programs, the dynamic allocation of stacks is not encouraged! The allocation of heap space is always dynamic, although all data space is released back to the system at the end of the program, but the precise application memory/release memory > match is the basic element of good program.
This is what I collect on stacks and stacks ~
---------------------------------------------------------------
The heap is managed by the programmer, and the stack is system managed.
---------------------------------------------------------------
---------------------------------------------------------------
---------------------------------------------------------------
In addition, some questions about static and global
Characteristics of static variables:
1, one storage: Static local variables are only initialized once, the next initialization, based on the last result value, is somewhat similar to a static member variable of a class in C + +, that is, regardless of how many instance objects the type generates, all objects share a static variable, and here is how many times the function is called, The static variable is initialized only once and is not destroyed because it is beyond its lifetime, but is not externally visible, illustrated by an example:
Copy Code code as follows:

void fun1 (int v)
{
static int value = V;
static int value = V;
}
int main (int arc, Char *args[])
{
FUN1 (50);
FUN1 (100);
}

The results of the execution are: value:50 value:50
Indicates that the initialization value of the second call to FUN1 () is the value of the last value, and the storage space of value in the static area is not released because of the end of Fun1 (), which embodies a storage;
2, scope limit: Static modification of the scope of the function is reflected in the function and variable;
A for functions, any function that is decorated with static, its scope is only the current source file, and for external purposes this function is invisible, that is, only functions in the same source file can call this static function; Conversely, if a function is called only by other functions in the same source file, Then this function should be declared static, the advantage of this is: to some extent, to solve the problem of the naming of functions between different source files;
b for variables, static modified global variables, only valid in the current source file, not visible externally, external files can not be referenced;
As the name suggests, a global variable is a variable that can be referenced globally, relative to a local variable, or an external variable; As with static variables, global variables are in static data areas, global variables are defined in one place, multiple references are referenced, and "external" variables are referenced using the keyword "extern".
Global variables can also be static, as previously noted, the meaning of static global variables is not to let "external" references, is a single source file in the global variable, that is, the compile phase of the global variable, not the connection phase of the global variables.
Through the above analysis, we are not difficult to draw the following conclusions:
1. The difference between a static function and a normal function is that a static function cannot be called by a function other than the same source file.
2. The difference between static local variables and ordinary local variables is that static local variables are initialized only once, and the next initialization is actually the last variable;
3. The difference between a static global variable and a normal global variable is that the scope of a static global variable is limited to the source file in which it resides.
---------------------------------------------------------------
---------------------------------------------------------------
---------------------------------------------------------------
local variables, global variables, static variables
The type descriptor for a static variable is static. Static variables are, of course, static storage, but the amount of static storage is not necessarily static variables, such as external variables are static storage mode, but not necessarily static variables, must be defined by static to become static external variables, or static global variables. For an automatic variable, it belongs to the dynamic storage mode. But you can also use static to define it as a static automatic variable, or a static local variable, thus becoming a statically stored mode.
In this view, a variable can be explained by static and change its original storage mode.
1. Static local Variables
A static local variable is formed by adding the static descriptor before the description of the local variable.
For example:
Copy Code code as follows:

static int a,b;
static float array[5]={1,2,3,4,5};

Static local variables, which are static storage, have the following characteristics:
(1) Static local variables are defined within functions, but not as automatic variables, which exist when called, and disappear when the function exits. Static local variables always exist, meaning that its lifetime is the entire source program.
(2) The lifetime of a static local variable is the entire source program, but the scope is still the same as the automatic variable, that is, it can only be used within the function that defines the variable. After exiting the function, it cannot be used, although it continues to exist.
(3) allows the initial value to be assigned to the static local amount of the constructed class. If the initial value is not assigned, the system automatically assigns a value of 0.
(4) If the static local variable of the basic type is not assigned an initial value in the description, the system automatically assigns 0 values. For an automatic variable, the value is indeterminate. According to the characteristics of static local variables, it can be seen that it is a lifetime of the entire source program. Although it cannot be used after leaving the function that defines it, it can continue to work when the function that defines it is invoked again, and the value left after the previous call is saved. Therefore, you can consider static local variables when you call a function multiple times and require the values of certain variables to be preserved between calls. Although the above goal can be achieved with global variables, global variables sometimes cause unexpected side effects, so it is advisable to adopt local static variables
2. Static Global Variables
The description of the global variable (external variable) before being labeled static constitutes a static global variable. The global variable itself is the static storage mode, static global variables are of course also static storage mode. The two are not different in the way they are stored. The difference between the two is that the scope of the Non-static global variable is the entire source program, and when a source program consists of multiple source files, non-static Global variables are valid in each source file. A static global variable restricts its scope, that is, it is only valid within the source file that defines the variable, and it cannot be used in other source files of the same source program. Because the scope of a static global variable is limited to one source file, it can only be common to functions within that source file, so it is possible to avoid causing errors in other source files. From the above analysis, we can see that the change of the local variable to the static variable is the change of its storage mode that changes its lifetime. Changing the global variable to a static variable changes its scope and limits its use. So the static this specifier plays a different role in different places. Should be taken into consideration.
Static Variables
In addition to scope, variables also have lifetimes, during which the variables retain their value. The values of module-level and public variables are maintained throughout the lifetime of the application. However, for local variables declared by Dim and procedures for declaring local variables, these local variables exist only if the procedure is executing. Typically, when a procedure is executed, the value of its local variable is no longer present, and the memory occupied by the variable is freed. When the procedure is executed the next time, all its local variables are reinitialized.
However, you can define a local variable as static, thus preserving the value of the variable. Declaring one or more variables within a procedure with the Static keyword is exactly the same as the Dim statement:
Static Depth
For example, the following function adds the previous operating value stored in the static variable accumulate to a new value in order to calculate the total value of the operation.
Copy Code code as follows:

Function runningtotal (num)
Static ApplesSold
ApplesSold = applessold + num
RunningTotal = ApplesSold
End Function

If you use Dim instead of a Static declaration of ApplesSold, the previous cumulative value is not preserved by calling the function, and the function simply returns the same value that called it.
The same effect is achieved by declaring ApplesSold in the module's declaration segment and making it a module-level variable. However, once this method changes the scope of the variable, the process is no longer exclusive access to the variable. Because other processes can also access and change the values of variables, the total value of the operation may be unreliable and the code will be more difficult to maintain.
declare all local variables to be static variables
In order for all local variables in the procedure to be static variables, you can add the static keyword at the beginning of the procedure header. For example:
Copy Code code as follows:

Static Function runningtotal (num)

This causes all local variables in the procedure to become static, whether they are declared with static, Dim, or Private, or implicitly. You can place the Static in front of any Sub or funtion procedure header, including the event procedure and the procedure declared Private.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.