Summary of global variables and local variables in C Language

Source: Internet
Author: User
Tags define local variable scope

1. Can a local variable be renamed with a global variable?
A: Yes. Global blocking will be performed in some cases. To use global variables, you must use "::"
A local variable can have the same name as a global variable. A local variable with the same name is used when this variable is referenced in a function, instead of a global variable. For some compilers, multiple local variables with the same name can be defined in the same function. For example, a local variable with the same name can be defined in both loops, the scope of the local variable is in that loop.
2. How to reference a defined global variable?
Answer: extern
You can use the header file reference method or the extern keyword. If you use the header file reference method to reference a global variant declared in the header file, assume that you have written the variant incorrectly, an error will be reported during compilation. If you reference it using the extern method, if you make the same mistake, no error will be reported during compilation, but an error will be reported during connection.
3. Can global variables be defined in header files that can be contained by multiple. C files? Why?
A: Yes. You can declare global variables with the same name in static form in different C files.
You can declare a global variable with the same name in different C files, provided that only one of them can assign an initial value to this variable in the C file, and the connection will not go wrong at this time.
4. What is the difference between static global variables and common global variables?What is the difference between static local variables and common local variables? What is the difference between a static function and a common function?
The description of global variables (external variables) is preceded by static to form a static global variable. Global variables are static storage, and static global variables are also static storage. The two are not different in storage methods. The difference between the two lies in that the scope of non-static global variables is the entire source program. When a source program is composed of multiple source files, non-static global variables are valid in each source file. The static global variable limits its scope, that is, it is valid only in the source file defining the variable, and cannot be used in other source files of the same source program. Because the scope of static global variables is limited to one source file, they can only be shared by functions in the source file. Therefore, errors in other source files can be avoided.

From the above analysis, we can see that after a local variable is changed to a static variable, its storage mode is changed, that is, its survival time is changed. After changing a global variable to a static variable, it changes its scope and limits its scope of use.

Static functions have different scopes than normal functions. They are only available in this file. Only functions used in the current source file should be declared as internal functions (static). Internal functions should be described and defined in the current source file. For functions that can be used outside the current source file, it should be described in a header file that the source file to use these functions must contain this header file.
What is the difference between static global variables and common global variables? static global variables are only made once to prevent being referenced in other file units;
What is the difference between static local variables and common local variables: static local variables are initialized only once, and the next time is based on the previous result value;
What is the difference between a static function and a common function: the static function has only one copy in the memory, and the common function maintains one copy in each call.
5. Local variables of the program exist in the (stack), Global variables exist in (static zone), and dynamic application data exist in (HEAP.
Variables can be described in three places in the program: internal functions, parameter definitions of functions, or all external functions. Variables can be divided into local variables, formal parameters, and full variables according to their defined locations. From the perspective of space, variables can be divided into global variables and local variables. From the perspective of time, static and dynamic storage variables can be divided.
I. global variables and local variables
1. Local Variables
The variable scope defined in the function is the function that defines the local variable. That is to say, it can only be used in the function that defines the local variable.
It is worth noting that the variable is generated only when the program is executed to define its module. Once the execution exits this module, the variable disappears.Copy codeThe Code is as follows: func ()
{
Int x; the scope of local variable x is very clear
......
}

2. Global Variables
Always valid during Program ExecutionCopy codeThe Code is as follows: int x = 1;
Func ()
{
X = x + 1;
}
Func1 ()
{
X = X-1;
}
Main ()
{
}

It is not difficult to see the range of integer x.
If the global variable is not initialized during definition, the system automatically assigns a value to the global variable. The numeric value is 0. The numeric value is null. '/0'
Disadvantages of global variables increase memory overhead and reduce the versatility of functions
When defining a global variable, the ideal position is at the beginning of the file. When these functions and some functions in other source files in the same program need to use the global variable, use extern for the variable within the function. it indicates that it is external.
(More details are required here)Copy codeThe Code is 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 external variables and the definition of global variables are not the same thing.
The description of the external variable only declares that the variable is referenced here as a global variable defined externally, and the definition of the global variable is to allocate storage units to the start.
A global variable can be defined only once but can be referenced multiple times.
* ** In the same source file, when the global variable and the local variable have the same name, the global variable does not work within the scope of the local variable.
2. Static and Dynamic Storage Variables
Variables that dynamically allocate buckets as needed during the program running are dynamic storage variables.
Static storage variables are used for variables that occupy fixed memory permanently during the running of the program.
It should also be noted that the instruction code of the program is the static storage variable stored in the code area of the program. The static storage variable is stored in the static data area, including global variables, and the dynamic storage variable of the program is stored in the dynamic data area. for example, the function parameters and the return address when the function is called.
Iii. Variable Storage Classification in C Language
Auto
Auto is called an automatic variable. If the function does not provide other instructions, it is an automatic variable.
Static
Static is called a static variable. Variable types can be divided into static local variables and static full-process variables.
1. Static local variables
It differs from a local variable in that this variable always exists when the function exits, but cannot be used by other functions. When you enter the function again, the last result is saved. Others are the same as local variables.
2. Static full-Process Variables
Turbo C2.0 allows large programs to be divided into several independent module files for separate compilation, and then the target files of all modules are connected together to increase the compilation speed and facilitate software management and maintenance. Static full-process variables are variables that are visible only in the defined source file but not in other source files. It differs from full-Process Variables in that full-process variables can be described as external variables (extern) and used by other source files, but static full-Process Variables cannot be described as external variables, that is, it can only be used by the source file.
Extern
Extern is called an external variable. To enable variables to be used by other files, in addition to defining its source files. Therefore, the full variables must be notified to every program module file, which can be described by extern.Copy codeThe Code is as follows: File 1 is file1.c
Int I, j;/* define full variables */

Char c;
Void func1 (int k );

Main ()
{
Func1 (20);/* call a function */
Func2 ();
.
.
.
}
Func1 (int k)/* User-Defined Function */
{
J = k * 100;
}
File 2 is file2.c
Extern int I, j;/* indicates that I and j are copied from File 1 */
Extern char c;/* Copy c */
Func2 ()/* User-Defined Functions */
{
Static float k;/* define static variables */
I = j * 5/100;
K = I/1.5;
.
.
.
}

For the above two files file1.c and file2.c, use the integrated development environment of Turbo C2.0 for compilation.
When connecting, you should first create a. prj file. For example, file. prj. The content of this file is as follows:
File1.c
File2.c
Then, write the file Name of file. prj to the Project Name in the main menu Project. Use F9 again
Compile the connection to upload an executable file named fioe.exe.
Register
Register is called a register variable. It can only be used for integer and balanced variables. The variables described by the register operator are stored in the CPU registers by Turbo C2.0, rather than in the memory as normal variables, which improves the computing speed. However, Turbo C2.0 only allows two register variables to be defined at the same time. Once more than two register variables are defined, the compiler automatically treats register variables that exceed the limit as non-register variables. Therefore, register variables are often used where the same variable name frequently appears.
In addition, the register variable is only applicable to the form parameters of local variables and functions. It is an auto variable,
Therefore, it cannot be used as a full-process variable. You can define an integer register variable as follows:
Register int;
The variables and Storage types described above will be further understood in the future through the definition and use of routine programs.
1. memory area of the program
Not all variables are known at all times. Some variables are visible throughout the program. They are called global variables. Some variables can only be known in one function, called Local variables. To understand these attributes of variables, you should first find out the distribution area of the program in the memory, as shown in Figure 5-2.
Figure 5-2 area of the program in memory
A program divides the memory blocks allocated to the operating system into four areas:
(1) The code area stores the code of the program, that is, each function code block in the program.
(2) The global data area stores the global data and static data of the program.
(3) The heap area stores dynamic program data.
(4) The stack area stores the local data of the program, that is, the data in each function.
2. Global Variables
Variables accessed outside the function are considered global variables and visible in each function of the program. Global variables are stored in the global data area of the memory. Global variables are created by the compiler and initialized to 0, except for special initialization when defining global variables.
For example, the following code defines and uses global variables. :Copy codeThe Code is as follows: int n = 5; // global variable
Void main ()
{
Int m = n;
//...
}
Void func ()
{
Int s;
N = s;
//...
}

N is defined externally in any function. N is initialized to 5. If n is not defined, C ++ initializes it to 0. The main () function uses the variable n1, and the function func () modifies the Variable n. Both functions access the same memory area. Global variables defined in this way. All functions are visible. If a function modifies n, all other functions will see the modified variable.
Global variables exist before the main function main () is run. Therefore, the main function can access the n variable. Global variables are usually defined at the top of the program. Once defined, global variables are known anywhere in the program. Global variables can be defined anywhere in the program, but outside of any function. All function definitions before the global variable definition do not know the variable. For example:Copy codeThe Code is as follows: void main ()
{
Int m = n; // error: n is not defined
//...
}
Int n; // global variable
Void func ()
{
Int s = 3;
N = s;
//...
}

The global variable n in this Code cannot be accessed by the main function main. Compiling this code will cause the m initialization statement in main () to report an "n undefined" error.
3. Local Variables
Variables defined in the function are only visible in the function. In addition, the type modification of a local variable is auto, indicating that the variable is allocated space in the stack, but auto is omitted in habits. For example:Copy codeThe Code is as follows: void main ()
{
Int n; // equivalent to auto intn;
//...
}
Void func ()
{
Int n;
//...
}

Both functions in the Code contain a variable definition statement. The variables defined in the function are partial to the function. The main () function has a variable n, and the func () function also has a variable n, but they are two variables at different positions.
A function can define any name for a local variable without worrying that other functions use the same name. This feature and the existence of local variables make C ++ suitable for programming projects involving multiple programmers. The Project Administrator specifies the function writing task for the programmer and provides parameters and expected return values for the program. Then, the programmer starts to write functions without having to understand other components of the program and the variable names used by other programmers in the project.
The local variables in the function are stored in the stack area. When a function starts to run, the local variable is allocated space in the stack. When the function exits, the local variable disappears.
Local variables are not initialized. If a local variable is not explicitly initialized, its content is unpredictable. For example:Copy codeThe Code is 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 running result is:
12345
The main function main () calls the functions func1 () and func2 () successively. They are all functions without 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, after the variable value is returned, the value is output in the main function, but it is found to be 12345, Which is the value initialized in funcl () function. This indicates that in func2 (), the local variable m is not explicitly initialized, and C ++ is not initialized by default, and its value is reserved as the value of the original memory location. So why does the original memory location happen to be where the storage value is 12345? See "function call mechanism" in the next section ".
Key points:
1. Global variables:
(1) Definition outside Function
(2) global visibility
(3) generally defined at the top of the program
(4) stored in the global data area of the memory
(5) If not initialized during definition, the value is 0.
(6) If a function modifies n, all other functions will see the modified variable.
2. Local variables:
(1) Internal Function Definition
(2) only visible in this function
(3) stored in the stack. 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 content is unpredictable.
Local variable
Local variables are also called internal variables. Local variables are defined in the function. Its scope is limited to the function. It is invalid to use this variable after leaving the function.
Local variables can be divided into dynamic and static storage types.
Local variables of the dynamic storage type are dynamically allocated storage space, and data is stored in the dynamic storage area (stack. The function is automatically released after the function call ends. The lifetime is the execution process of the function that declares the variable.
Local variables of the static storage type are static storage space allocated, and data is stored in the static storage area. The program is not released during the entire running period, and the lifetime runs throughout the entire process of running the program.
If the local variables in the function are not specifically declared as static storage classes, the storage space is dynamically allocated by default. auto is omitted by default during variable declaration.
Global Variables
Global variables, also known as external variables, are defined outside the function. Their scope is from the definition of variables to the end of the program file. Global variables are all stored in the static storage area. When the program starts to execute, the global variables are allocated to the storage area, and the program is released after the row is complete. They occupy a fixed storage unit during program execution without Dynamic Allocation and release;
If the external variable is not defined at the beginning of the file, its effective scope is limited to the end of the file at the definition.
If the function before the definition point wants to reference this external variable, you should use the keyword extern to declare this variable before the reference ". This variable is an external variable that has been defined. With this declaration, you can legally use this external variable from the "Declaration. Its effective scope is extended from the extern Declaration of the file to the end of the file.
If the keyword static is added before the global variable declaration, other files cannot access and use the variable. the effective scope of the variable is only limited to the final part of the definition.
Can a local variable be renamed with a global variable?
Local variables can be renamed with global variables, but local variables block global variables. When this variable is referenced in a function, local variables with the same name are used instead of global variables.
PS: The global variables declared for extern are the same..
---------------------------------------------------------------
Generally, global variables are stored in the data zone, and local variables are stored in the stack zone,
Dynamic variables are stored in the heap area, and function code is stored in the code area.
---------------------------------------------------------------
The stack area is a common stack data structure. It complies with the LIFO post-first-in-first-out rules and local variables are arranged there as defined in ASM, so that the stack can be balanced after a function is completed, simple operation and High Efficiency
The heap (Dynamic zone) here should be called a stack (do not mix with the heap in the data structure), which is a block generated by the program during compilation to generate dynamic memory allocation, stack operations are much more troublesome, the optimal address should be determined during allocation (to prevent useless memory fragments from being generated (due to repeated NEW and DELETE requests, small spare memory in the memory of the two blocks being used (not easily allocated) )), the allocation and recycling efficiency is much lower than the stack efficiency.
---------------------------------------------------------------
Stack is a function provided by the system. It features fast and efficient. Its disadvantage is that it has restrictions and data is not flexible. Stack is a function provided by function libraries. It features flexibility and convenience and wide range of data adaptation, but the efficiency is reduced. The stack is the system data structure, which is unique for processes/Threads. The heap is the internal data structure of the function library, which is not necessarily unique. Memory allocated by different heaps cannot be operated on each other. Stack space is divided into static allocation and dynamic allocation. Static allocation is completed by the compiler, such as automatic variable allocation. Dynamic Allocation is completed by the alloca function. The stack does not need to be released dynamically (automatically), so there is no release function. For the sake of porting> Programs, dynamic stack allocation is not encouraged! Heap space allocation is always dynamic. Although all data spaces are released back to the system at the end of the program, precise memory allocation and memory allocation are the basic elements of a good program.
This is my favorite content for Stack and stack ~
---------------------------------------------------------------
Stacks are managed by programmers and stacks are managed by systems.
---------------------------------------------------------------
---------------------------------------------------------------
---------------------------------------------------------------
Other static and global problems:
Static variables:
1. One storage: static local variables are initialized only once. The next Initialization is based on the previous result value, which is somewhat similar to static member variables of c ++ classes, that is, no matter how many instance objects are generated for this type, all objects share a static variable. Here, no matter how many times this function is called, this static variable is initialized only once, it is not destroyed because it exceeded its lifetime, but is invisible to the outside. It is illustrated in an example:Copy codeCode: void fun1 (int v)
{
Static int value = v;
Static int value = v;
}
Int main (int arc, char * args [])
{
Fun1 (50 );
Fun1 (100 );
}

The result is: value: 50 value: 50.
It indicates that the initialization value when fun1 () is called for the second time uses the value of the previous value. The storage space of value in the static zone is not because of fun1 () and is released, that is, a storage;
2. scope limitation: the static modified scope limitation function is reflected in both functions and variables;
A) For a function, the scope of any function modified with static is only the current source file, but this function is invisible to the outside, 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, the function should be declared as static, the benefit of doing so is that the naming conflicts between functions of different source files can be solved to some extent;
B) For variables, the static global variables are only valid in the current source file and invisible to the outside and cannot be referenced by the external files;
As the name implies, global variables refer to variables that can be referenced globally. Compared with local variables, global variables are also called external variables. Like static variables, global variables are located in the static data zone and are defined in one place, multiple references: Use the keyword "extern" to reference the variable "external.
Global variables can also be static. As mentioned above, static global variables mean that they are not referenced by "external". They are the global variables in a single source file, that is, the global variables in the compilation phase, instead of global variables in the connection phase.
Through the above analysis, we can draw the following conclusions:
1. The difference between static functions and common functions is that static functions cannot be called by functions other than the same source file.
2. The difference between static local variables and common local variables is that static local variables are initialized only once, And the next Initialization is actually the last variable;
3. The difference between static global variables and common global variables is that the scope of static global variables is limited to the source files.
---------------------------------------------------------------
---------------------------------------------------------------
---------------------------------------------------------------
Local variables, global variables, static variables
The type description of static variables is static. Static variables are of course static storage, but the amount of static storage is not necessarily static variables. For example, although external variables are static storage, they are not necessarily static variables, A static external variable, or a static global variable, must be defined by static. For automatic variables, it is a dynamic storage method. However, static variables can also be defined as static automatic variables, or static local variables, to become a static storage method.
From this point of view, a variable can be re-described by static and its original storage method can be changed.
1. Static local variables
Add the static identifier before the local variable description to form a static local variable.
For example:Copy codeThe Code is as follows: static int a, B;
Static float array [5] = {1, 2, 3, 4, 5 };

Static local variables are stored in static mode and have the following features:
(1) Static local variables are defined in the function, but they do not exist when called as automatic variables, and disappear when you exit the function. Static local variables always exist, that is, their lifetime is the entire source program.
(2) Although the lifetime of the static local variable is the entire source program, its scope is still the same as that of the automatic variable, that is, the variable can only be used within the function that defines the variable. After exiting the function, although the variable still exists, it cannot be used.
(3) allow initial values to be assigned to the static local volume of the constructor class. If the initial value is not assigned, the system automatically assigns the value 0.
(4) If an initial value is not assigned to a static local variable of the basic type, the system automatically assigns the value 0. If the initial value is not assigned to the automatic variable, the value is not fixed. According to the characteristics of static local variables, it can be seen that it is a kind of lifetime for the entire source program. Although this function cannot be used after it is defined, it can continue to be used when the function is called again, and the value left after the previous call is saved. Therefore, when you call a function multiple times and require that the values of some variables be retained between calls, you can consider using static local variables. Although global variables can achieve the above purpose, global variables sometimes cause unexpected side effects. Therefore, it is recommended to use local static variables.
2. Static global variables
The description of global variables (external variables) is preceded by static to form a static global variable. Global variables are static storage, and static global variables are also static storage. The two are not different in storage methods. The difference between the two lies in that the scope of non-static global variables is the entire source program. When a source program is composed of multiple source files, non-static global variables are valid in each source file. The static global variable limits its scope, that is, it is valid only in the source file defining the variable, and cannot be used in other source files of the same source program. Because the scope of static global variables is limited to one source file, they can only be shared by functions in the source file. Therefore, errors in other source files can be avoided. From the above analysis, we can see that after a local variable is changed to a static variable, its storage mode is changed, that is, its survival time is changed. After changing a global variable to a static variable, it changes its scope and limits its scope of use. Therefore, the description of static plays different roles in different places. Attention should be paid.
Static variables
In addition to the range, variables also have a retention period, during which variables can maintain their values. The value of module-level variables and public variables remains unchanged during the application's survival period. However, for Dim declared local variables and declared local variables, these local variables only exist when the process is executed. Generally, when a process is completed, its local variable value does not exist and the memory occupied by the variable is also released. When this process is executed, all its local variables will be reinitialized.
However, you can define local variables as static variables to retain the value of the variables. In the process, use the Static keyword to declare one or more variables, which is exactly the same as the Dim statement:
Static Depth
For example, the following function adds the previous total operating value stored in the static variable Accumulate to a new value to calculate the total operating value.Copy codeThe Code is as follows: Function RunningTotal (num)
Static ApplesSold
ApplesSold = ApplesSold + num
RunningTotal = ApplesSold
End Function

If you use Dim instead of Static declaration of ApplesSold, the previous cumulative value will not be retained by calling the function, and the function will simply return the same value that is called.
Declare ApplesSold in the declaration section of the module and make it a module-level variable. This will also achieve the same effect. However, once this method changes the scope of the variable, the process no longer exclusively accesses the variable. Because other processes can also access and change variable values, the total operating value may be unreliable and the code will be more difficult to maintain.
Declare all local variables as static variables
To make all local variables in the process Static, you can add the Static keyword at the beginning of the process header. For example:Copy codeThe Code is as follows: Static Function RunningTotal (num)

This changes all local variables in the process to Static, Whether Declared in Static, Dim, or Private or implicitly. Static can be placed before any Sub or Funtion process header, including the event process and the process whose name is Private.

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.