Understanding of static variables

Source: Internet
Author: User

Turn from DZQABC large static variable understanding

The static variable type descriptor is static.

Static variables are static storage, where the storage space is a static data area in memory (a storage unit is allocated in a static store), and the data in that region occupies the storage space throughout the program's run (not released during the entire run of the program), or it can be considered as its memory address To the end of the entire program run (instead, the auto automatic variable, dynamic local variable, belongs to the dynamic storage category, which accounts for dynamic storage space, which is released after the function call ends). A static variable is always present throughout the execution of a program, but is not available outside its scope.

In addition, the amount of static storage is not necessarily a static variable. For example, an external variable is statically stored, but not necessarily a static variable, which must be defined by static to become a static external variable, or a static global variable.

All global variables are static variables, and local variables are local static variables only when they are defined with the type modifier static.

Static variables can be applied wherever they can be applied, and once the application is successful, it will no longer accept the same application.

A static variable does not mean that it cannot change the value, and the amount of the value cannot be changed is called a constant. The value it has is mutable, and it maintains the most recent value. It is static because it does not change as the function calls and exits. That is, when the function was last called, if we assign a value to a static variable, the value remains unchanged the next time the function is called.


Static local variables:

1, static class internal variables, like Auto Auto variables (that is, non-Static declared local variables), is a local variable of a particular function, that is, you can only use the variable within the function that defines the variable, the scope of the 2 is the same The difference between the two is that the auto variable will exist and disappear with the function being called and exited, and the static class local variable will persist regardless of whether its function is called or not, although the variable continues to exist but cannot be used. If the function that defines it is called again, it can continue to be used, and the value left after the previous call is saved. In other words, the intrinsic variable of the static type is a variable that can only be used in a particular function but occupies the storage space.

2. If a static variable is initialized at the same time that the function body is defined, then the program is no longer initialized (the static variable initialization statement of the underlying type that appears inside the function is executed only on the first call). The initial value of an automatic variable is performed at the time of the function call, and each call to the function is given an initial value, which is equivalent to executing an assignment statement.

3, the initialization expression for a static local variable must be a constant or constant expression. Even if the local static variable is defined without an initial value, the system automatically assigns the initial values of 0 (to numeric variables) or null characters (to character variables), and the static variable is initially 0. For auto variable auto, if the initial value is not assigned, it will be an indeterminate value.

4, consider using static local variables when you call a function multiple times and require the values of certain variables to be preserved between calls. Although this can be achieved with global variables, global variables sometimes cause unintended side effects, so it is advisable to use local static variables.

Note: Local static variables take longer memory time and are less readable, so avoid using local static variables unless necessary.

Example:

//Examine the value of the static local variable.


# include < stdio. h> 

Int f ( int a)  

    auto b = 0; 
    static  c = 3; 

    b = b + 1; 
     c = c+ 1; 
    return  ( a+ b+  c)  ; 


Main ( )  

    int a  = 2, i; 

    for  ( i = 0; i <  3; i + + )  
        printf  (   "%d\n"  , f ( a)  )  ; 
}

//求1~5的阶乘。

/*
由于f为静态变量,能在每次调用后保留其值并在下一次调用时继续使用,所以输出值成为累加的结果。若变量f说明为自动变量(去掉static),当main中多次调用factor时,f均赋初 
The value is 1, so each output value is 1.
*/

# include < stdio. H>

Long factor (int n)
{
static long int f = 1; Static
f * = n;
return F;
}

Main ()
{
int i;
for (i = 1; i < = 5; i+ +)
printf ("%ld\n", Factor (i));
}


Second, static global variables

A static global variable is formed by the description of the global variable (external variable), preceded by static.
Global variables themselves are static storage, and static global variables are, of course, static storage methods.
The two are not different in how they are stored.

The difference between the two is:
1, the scope of the non-static global variable is the whole source program, when a source program consists of multiple source files, non-static global variables are valid in each source file.
2. A static global variable restricts its scope, which is valid only within the source file that defines the variable, and cannot be used in other source files of the same source program (that is, the CPP file that declares the variable or the CPP file that contains the variable declaration header file).

Because the scope of a static global variable is limited to one source file, it can be common only for functions within that source file, so you avoid causing errors in other source files.

From the above analysis can be seen ————
Changing the local variable to a static variable changes the way it is stored, that is, it changes its lifetime.
Changing a global variable to a static variable changes its scope and limits its scope of use.

So the function of the static descriptor is different in different places. Should be taken into consideration.

About the Static keyword
1. Static variables, allocated in the static storage area, in the data segment. The value of the variable does not change after the function exits.
2. Scope, global static variables, static functions can only be used in this file. (different from general global variables)
Local static variables and local variables of the same function

Five memory partitions (seemingly different from the compiler principle, but the truth is the same, the actual existence of things will always have a certain gap with the theory)
1. In C + +, memory is divided into 5 zones, each of which are heap, stack, free storage, global/static storage, and constant storage.
2. Stacks are the stores of variables that are allocated by the compiler when needed, and that are automatically clear when not needed. The variables inside are usually local variables, function parameters, and so on.
3. Heap, which is the memory blocks allocated by new, their release compiler does not go to the tube, by our application to control, generally a new will correspond to a delete. If the programmer does not release it, the operating system will automatically recycle after the program finishes.
4. The free storage area, which is the memory blocks allocated by malloc, is very similar to the heap, but it ends up living with no.
5. Global/static storage, global variables and static variables are allocated to the same piece of memory, in the previous C language, the global variables are divided into initialized and uninitialized, in C + + There is no such distinction, they occupy the same chunk of memory.
6. Constant storage, this is a more special storage area, they are stored in a constant, not allowed to modify (of course, you have to pass the improper means can also be modified, and many methods)


Other than that:

1 static variables are placed in the program's Global store (that is, in the program's global data area instead of being allocated on the stack, so it does not cause a stack overflow), so that the original assignment can be maintained at the next call. This is the difference between a stack variable and a heap variable.

2) static variable tells the compiler with static that it is visible only within the scope of the variable. This is the difference between it and the global variable. -The role of information concealment. (an external static declaration can also be used to declare a function.) If a function is declared as a static type, the function name cannot be accessed except for the file in which the function declaration is visible. )

3), if the global variables are only accessed in a single C file, you can change this variable to a static global variable to reduce the coupling between modules;
If the global variable is accessed only by a single function, you can change this variable to a static local variable of the function to reduce the coupling between the modules.


4), designing and using functions that access dynamic global variables, static global variables, and static local variables, you need to consider the reentrant problem.
The so-called "reentrant" (which can be said to be predictable) is that the same output should be produced as long as the input data is the same.

A static variable is used in the function because of the characteristics of the static variable, which is called a function with the "internal memory" function.

If we need a reentrant function, then we must avoid using the static variable in the function, the static variable in this function, using the principle that it can not be used as much as possible.

Of course, there are times when a static variable must be used in a function, such as when the return value of a function is a pointer type, the address of a static local variable must be the return value, and if it is the auto type, it is returned as the wrong pointer.

Understanding of static variables

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.