Exploring the storage location of local variables and global variables in C language in memory

Source: Internet
Author: User

Storage Class of local variables and global variables in C Language (static, extern, auto, register)

1. Local and global variables
As mentioned in the discussion of the parameter variables of a function, the parameter variables are allocated memory units only during the call period, and are released immediately after the call ends. This indicates that the parameter variable is valid only within the function and cannot be used without the function. The valid range of the variable is the scope of the variable. All values in C language have their own scopes. Variables are described in different ways, and their scopes are also different. Variables in C language can be divided into local variables and global variables by scope.
1.1 local variables
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.
[Example 1.1]Copy codeThe Code is as follows: int f1 (int a)/* function f1 */
{
Int B, c;
}
Valid for a, B, and c
Int f2 (int x)/* function f2 */
{
Int y, z;
}
Valid for x, y, and z
Int main (void)
{
Int m, n;
}
M, n valid

In function f1, three variables are defined. a is the form parameter, B, and c are the general variables. Variables a, B, and c are valid in the range of f1, or a, B, and c are limited to f1. Similarly, the scope of x, y, and z is limited to f2. The scope of m and n is limited to the main function. The scope of local variables must also beNote the following:
1) The variables defined in the main function can only be used in the main function and cannot be used in other functions. In addition, the main function cannot use variables defined in other functions. Because the main function is also a function, it is in parallel with other functions. This is different from other languages and should be noted.
2) The parameter variable is a local variable of the called function, and the real variable is a local variable of the main function.
3) allow different functions to use the same variable names. They represent different objects, assign different units, do not interfere with each other, and avoid confusion. For example, in arguments, the variable names of the form and real parameters are all n, which is completely allowed.
4) variables can also be defined in composite statements, and their scope is only within the scope of composite statements.
[Example 1.2]Copy codeThe Code is as follows: int main (void)
{
Int s,;
{
Int B;
S = a + B;
/* B Scope */
}
/* S, a scope */
}

[Example 1.3]Copy codeThe Code is as follows: int main (void)
{
Int I = 2, j = 3, k;
K = I + j;
{
Int k = 8;
Printf ("% d \ n", k );
}
Printf ("% d \ n", k );
}

This program defines the I, j, and k variables in main, where k does not assign the initial value. In the composite statement, a variable k is defined and the initial value is 8. Note that these two keys are not the same variable. The k defined by main is used outside the composite statement, while the k defined in the composite statement is used in the composite statement. Therefore, the k of the program's 4th rows is defined as main, and its value should be 5. 7th rows output k value. This row is in the composite statement and takes effect from k defined in the composite statement. The initial value is 8, so the output value is 8, 9th rows output I, and k value. I is valid in the entire program. The value of row 7th is 3 For I, so the output is also 3. In addition to the compound statement, the output k of row 9th should be the k defined by main. the k value has been set to 5 from row 4th, so the output is also 5.

1.2 global variables
Global variables, also known as external variables, are defined outside the function. Which function does not belong to? It belongs to a source program file. Its scope is the entire source program. Use global variables in functions. Only global variables described in the function can be used. The description of the global variable is extern. However, the global variables defined before a function are not described in this function.
[Example 1.4]Copy codeThe Code is as follows: int a, B;/* external variable */
Void f1 ()/* function f1 */
{
......
}
Float x, y;/* external variable */
Int fz ()/* function fz */
{
......
}
Int main (void)/* main function */
{
......
}

From the above example, we can see that a, B, x, and y are all external variables defined outside the function, and they are all global variables. However, x and y are defined after the f1 function, and there is no description of x and y in f1, so they are invalid in f1. A and B are defined at the beginning of the source program. Therefore, they can be used without instructions in f1, f2, and main.
[Example 1.5] enter the length, width, and height of the cube, w, and h. Calculate the volume and the area of the three sides x * y, x * z, and y * z.Copy codeThe Code is as follows: int s1, s2, s3;
Int vs (int a, int B, int c)
{
Int v;
V = a * B * c;
S1 = a * B;
S2 = B * c;
S3 = a * c;
Return v;
}
Int main (void)
{
Int v, l, w, h;
Printf ("\ ninput length, width and height \ n ");
Scanf ("% d", & l, & w, & h );
V = vs (l, w, h );
Printf ("\ nv = % d, s1 = % d, s2 = % d, s3 = % d \ n", v, s1, s2, s3 );
}

[Example 1.6] The external variable has the same name as the local variable.Copy codeThe Code is as follows: int a = 3, B = 5;/* a, B is the external variable */
Max (int a, int B)/* a, B is the external variable */
{
Int c;
C = a> B? A: B;
Return (c );
}
Int main (void)
{
Int a = 8;
Printf ("% d \ n", max (a, B ));
}

If the external variable in the same source file has the same name as the local variable, the external variable is "blocked" within the scope of the local variable, that is, it does not work.

2. Storage Class of Variables
2.1 dynamic storage and static dynamic storage
We have already introduced that, from the perspective of the scope of variables (that is, from the perspective of space), they can be divided into global variables and local variables.
From another perspective, variable values can be divided into static storage mode and dynamic storage mode from the perspective of time (I .e. lifetime.
Static storage: it refers to the way to allocate a fixed storage space while the program is running.
Dynamic Storage: dynamically allocates storage space as needed during the program running.
User buckets can be divided into three parts:
1) Procedure area;
2) static storage area;
3) Dynamic Storage zone;
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;
The dynamic storage area stores the following data:
1) function form parameters;
2) Automatic variables (local variables without static Declaration );
3) field protection and return addresses of function calls;
For the above data, dynamic storage space is allocated when the function starts calling, and the space is released when the function ends.
In C, each variable and function has two attributes: Data Type and data storage type.

2.2auto variable
Local variables in the function, if not specifically declared as static storage classes, are dynamically allocated storage space, and data is stored in the dynamic storage area. The form parameters in the function and the variables defined in the function (including the variables defined in the composite statement) belong to this class. When the function is called, the system will allocate storage space to them, these buckets are automatically released at the end of the function call. These local variables are called automatic variables. Auto variables use the keyword auto for the storage class declaration.
[Example 1.7]Copy codeThe Code is as follows: int f (int a)/* defines the f function. a is the parameter */
{
Auto int B, c = 3;/* defines the automatic variables B and c */
}

A is the form parameter, B, c is the automatic variable, and the initial value of c is 3. After the f function is executed, the storage units a, B, and c are automatically released.
The keyword auto can be omitted. If auto is not written, it is implicitly set to "Automatic Storage category", which is a dynamic storage method.

2.3 use static to declare local variables
Sometimes you want the local variable value in the function to keep the original value without disappearing after the function call. In this case, you should specify the local variable as "static local variable" and declare it with the keyword "static.
[Example 1.8] evaluate the static local variable value.Copy codeThe Code is as follows: f (int)
{
Auto B = 0;
Static c = 3;
B = B + 1;
C = c + 1;
Return (a + B + c );
}
Int main (void)
{
Int a = 2, I;
For (I = 0; I <3; I ++)
Printf ("% d", f ());
}

Description of static local variables:
1) Static local variables belong to the static storage class and are allocated to storage units in the static storage area. The program is not released during the entire running period. Automatic variables (that is, dynamic local variables) belong to the dynamic storage class, occupying the dynamic storage space, and are released after the function call ends.
2) assign an initial value to a static local variable during compilation, that is, assign the initial value only once. Assign the initial value to an automatic variable when the function is called, and re-assign the initial value to each callback function, it is equivalent to executing a value assignment statement.
3) if initial values are not assigned when defining local variables, the initial values 0 (For numeric variables) or null characters (for character variables) are automatically assigned to static local variables during compilation ). For automatic variables, if the initial value is not assigned, its value is an uncertain value.
[Example 1.9] print the factorial value from 1 to 5.Copy codeThe Code is as follows: int fac (int n)
{
Static int f = 1;
F = f * n;
Return (f );
}
Int main (void)
{
Int I;
For (I = 1; I <= 5; I ++)
Printf ("% d! = % D \ n ", I, fac (I ));
}

2.4register variable
To improve efficiency, the C language allows you to place the value of a local variable in a register in the CPU. This variable is called a "register variable" and is declared using the keyword register.
[Example 2.0] use register variables.Copy codeThe Code is as follows: int fac (int n)
{
Register int I, f = 1;
For (I = 1; I <= n; I ++)
F = f * I;
Return (f );
}
Int main (void)
{
Int I;
For (I = 0; I <= 5; I ++)
Printf ("% d! = % D \ n ", I, fac (I ));
}

Note:
1) only local automatic variables and formal parameters can be used as register variables;
2) The number of registers in a computer system is limited, and multiple register variables cannot be defined;
3) Local static variables cannot be defined as register variables.

2.5 use extern to declare external variables
External variables (global variables) are defined outside the function. Their scope is from the definition of variables to the end of the program file. 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.
[Example 2.1] Use extern to declare external variables and extend the scope in the program file.Copy codeThe Code is as follows: int max (int x, int y)
{
Int z;
Z = x> y? X: y;
Return (z );
}
Int main (void)
{
Extern A, B;
Printf ("% d \ n", max (A, B ));
}
Int A = 13, B =-8;

Note:In the last line of the program file, the external variables A and B are defined. However, since the external variables are defined after the main function, external variables A cannot be referenced in the main function, b. Now, we use extern in the main function to declare the external variables A and B, and then we can legally use the external variables A and B from the Declaration.

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.