C/C ++ static keywords

Source: Internet
Author: User

Static variables are used in a file. Space is allocated at the beginning of the program, and space is released at the end of the program. The default value is 0, which can be changed during use.

Static variables or static functions can be accessed only by the code in this file. Their names are invisible to other files.
Usage 1: static variables declared inside the function can be used as a communication mechanism between objects.
If a local variable is declared as static, there will be only one static allocation object, which is used to represent this variable in all calls to the function. This object will be initialized only when the execution thread reaches its definition for the first time.
Usage 2: local static object
For a local static object, the constructor is called when the control thread first passes the definition of the object. At the end of the program, the destructor of local static objects will be called one by one in the reverse order they are constructed, without specifying the exact time.
Usage 3: static member and static member functions
If a variable is a part of a class but not a part of each object of the class, it becomes a static member. A static member has only one unique copy, instead of having one copy in each object as a regular non-static member. Similarly, a function that requires a member of the struct class and does not need to be called for a specific object is also called a static member function.
The static member function of a class can only be a static member (variable or function) of a class ).

Further details are as follows:

1. first introduce the first and most important one: Hide

When we compile multiple files at the same time, all global variables and functions without the static prefix are globally visible. I will give an example to illustrate this sentence. We need to compile two source files, A. C and Main. C.. The content of A. C is as follows:

Char A = 'a'; // global variable

Void MSG () {printf ("Hello \ n ");}

The content of Main. C is as follows:

Int main (void ){

Extern char a; // extern variable must be declared before use

Printf ("% C", );

(Void) MSG ();

Return 0 ;}

The running result of the program is:

A Hello

You may ask: why can the global variables A and MSG defined in A. C be used in Main. C? As mentioned above, all global variables and functions without the static prefix have global visibility, and other source files can also be accessed. In this example, A is a global variable, MSG is a function, and there is no static prefix. Therefore, it is visible to other source files main. C.

If static is added, other source files are hidden. For example, if static is added before the definitions of a and MSG, Main. C will not be able to see them. This feature allows you to define functions with the same name and variables in different files without worrying about name conflicts. Static can be used as the prefix of functions and variables. For a function, the role of static is limited to hiding. For a variable, static has the following two functions.

2. The second role of static is to keep the variable content persistent.

Variables stored in the static data area will be initialized at the beginning of the program, which is also the only initialization. There are two types of variables stored in the static storage area: global variables and static variables, but compared with global variables, static can control the visible range of variables. Static is used to hide the variables. Although this is not common, I will give an example.

# Include <stdio. h>

Int fun (void ){

Static int COUNT = 10; // In fact, this assignment statement has never been executed.

Return count --;

}

Int COUNT = 1;

Int main (void ){

Printf ("Global \ t \ tlocal static \ n ");

For (; count <= 10; ++ count)

Printf ("% d \ t % d \ n", Count, fun ());

Return 0 ;}

The running result of the program is:

Global local static
1 10
2 9
3 8
4 7
5 6
6 5
7 4
8 3
9 2
10 1

3. The third role of static is that the default Initialization is 0. In fact, global variables also have this attribute, because global variables are also stored in the static data zone.

In the static data area, the default values of all bytes in the memory are 0x00. In some cases, this feature can reduce the workload of programmers. For example, to initialize a sparse matrix, we can set all elements to 0 one by one, and assign values to elements other than 0. If it is defined as static, the first 0 operation is saved. Another example is to use a character array as a string, but it is too troublesome to add '\ 0' at the end of the character array each time. If the string is defined as static, it saves the trouble because it is '\ 0 '. Try a small experiment.

# Include <stdio. h>

Int;

Int main (void ){

Int I;

Static char STR [10];

Printf ("INTEGER: % d; string: (BEGIN) % s (end)", A, STR );

Return 0;

}

The running result of the program is INTEGER: 0; string: (BEGIN) (end)

Finally, we will summarize the three functions of static in one sentence. First, the main function of static is to hide. Secondly, because static variables are stored in static storage areas, they have persistence and default value 0.

4. Summary of functions and variables declared using static

Static declared variables have two features in the C language:

1) The variables will be placed in the global storage area of the program, so that the original values can be maintained during the next call. This is the difference between stack variables and heap variables.

2) The variable uses static to notify the compiler that it is only visible within the scope of the variable. This is the difference between it and global variables.

TIPS:
A. if the global variable is only accessed in a single c file, you can change the variable to a static global variable to reduce the coupling between modules;
B. If the global variable is only accessed by a single function, you can change the variable to the static local variable of the function to reduce the coupling between modules;
C. When designing and using functions that access dynamic global variables, static global variables, and static local variables, you must consider re-import;
D. If we need a reentrant function, we must avoid using static variables in the function (such a function is called a function with the "internal memory" function)
E. static variables must be used in a function. For example, if the return value of a function is of the pointer type, the address of the static local variable must be used as the return value. If the return value is of the auto type, the returned result is an error pointer.

Add static before the function to make the function a static function. However, the meaning of "static" here is not the storage method, but the scope of the function is limited to this file (so it is also called an internal function ). The advantage of using internal functions is that when different people write different functions, you don't have to worry about your own defined functions and whether they will have the same name as the functions in other files.

Extended analysis:

The term static has an unusual history. At first, the keyword static was introduced in C to indicate that a local variable still exists after exiting a block. Subsequently, static has a second meaning in C: Used to indicate global variables and functions that cannot be accessed by other files. To avoid introducing new keywords, the static keyword is still used to indicate the second meaning. Finally, C ++ reused this keyword and gave it a third meaning different from the previous one: variables and functions that belong to a class rather than any specific objects of this class (the same as the meaning of this keyword in Java ).

Differences between global variables, static global variables, static local variables, and local variables

Variables can be divided into global variables, static global variables, static local variables, and local variables.

(1) global variables, static global variables, and static local variables are stored in the static storage area of the memory, and local variables are stored in the stack area of the memory.

(2) By scope, global variables are valid throughout the project file; static global variables are valid only in the file defining them; static local variables are valid only in the defined functions, but only once the program allocates memory. After the function returns, the variable does not disappear. Local variables are valid in the defined functions, however, the function fails to return.

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.

(1) static functions have different scopes than normal functions. Only 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.

(2) What is the difference between static global variables and common global variables: static global variables are initialized only once to prevent being referenced in other file units;

(3) 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;
(4) What is the difference between a static function and a common function: a static function has only one copy in the memory, and a common function maintains one copy in each call.
(5) If the global variables and static variables are not manually initialized, the compiler initializes them to 0. The value of the local variable is unknown.

5. Static of C ++

The static function of C ++ has two usage methods: static for process programming and static in object-oriented programming. The former applies to common variables and functions, and does not involve classes. The latter mainly describes the role of static in classes.

(1) process-oriented static

1) Static global variables

Add the keyword static before the global variable, which is defined as a static global variable. Here is an example of a static global variable:

// Example 1

# Include <iostream. h>

Void FN ();

Static int N; // defines the static global variable.

Void main ()

{

N = 20;

Cout <n <Endl;

FN ();

}

Void FN ()

{

N ++;

Cout <n <Endl;

}

Static global variables have the following features:

I) The variable allocates memory in the global data zone;
Ii) non-initialized static global variables will be automatically initialized to 0 by the program (the value of the automatic variable is random unless it is explicitly initialized );
Iii) Static global variables are visible in the entire file that declares them, but invisible outside the file;

All static variables are allocated memory in the global data zone, including the static local variables to be mentioned later. For a complete program, the distribution in the memory is as follows:

Code Area

Global data Zone

Heap Area

Stack Zone

In general, dynamic data generated by new is stored in the heap zone, and automatic variables in the function are stored in the stack zone. Automatic variables usually release space as the function exits, and static data (even static local variables in the function) is stored in the global data zone. The data in the global data zone does not release space because the function exits. Careful readers may find that

Static int N; // defines the static global variable.

Change

Int N; // defines the global variable

The program runs normally. Indeed, defining global variables can share variables in files, but defining static global variables has the following benefits:

1) Static global variables cannot be used by other files;

2) variables with the same name can be defined in other files without conflict;

You can change the Sample Code as follows:

// Example 2

// File1

# Include <iostream. h>

Void FN ();

Static int N; // defines the static global variable.

Void main ()

{

N = 20;

Cout <n <Endl;

FN ();

}

// File2

# Include <iostream. h>

Extern int N;

Void FN ()

{

N ++;

Cout <n <Endl;

}

Compile and run example 2, and you will find that the above Code can be compiled separately, but an error occurs during running. Try

Static int N; // defines the static global variable.

Change

Int N; // defines the global variable

Compile and run the program again to understand the differences between global variables and static global variables.

(2) Static local variables

Before a local variable, add the keyword static to define the variable as a static local variable. Here is an example of static local variables:

// Example 3

# Include <iostream. h>

Void FN ();

Void main ()

{

FN ();

FN ();

FN ();

}

Void FN ()

{

Static n = 10;

Cout <n <Endl;

N ++;

}

Generally, a variable is defined in the function body, and stack memory is allocated to the local variable whenever the program runs the statement. However, as the program exits from the function body, the system will reclaim the stack memory and the local variables will also become invalid. But sometimes we need to save the variable value between two calls. The general idea is to define a global variable for implementation. In this way, the variable no longer belongs to the function itself, and is no longer only controlled by the function, causing inconvenience to program maintenance. Static local variables can solve this problem. Static local variables are stored in the global data zone, instead of in the stack. Each time the values are kept to the bottom

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.