Detailed description of static keywords in C + +

Source: Internet
Author: User

Static variables are scoped to a file, space is allocated at the beginning of the program, Space is freed at the end, default is initialized to 0, and its value can be changed when used.

static variables or static functions only the code in this file can access it, and its name is not visible in other files.
Usage 1: Static variables declared inside the function, which can act as a communication mechanism between objects
If a local variable is declared as static, then there will be only one statically allocated object, which is used to represent the variable in all calls to that function. This object will be initialized only at the execution thread's definition for the first time it arrives.
Usage 2: Local static objects
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 destructors for the local static objects are invoked in the reverse order in which they were constructed, with no exact time specified.
Usage 3: Static members and static member functions
If a variable is part of a class, but is not part of the object of the class, it becomes a static statically member. A static member has only one copy, rather than a regular non-static member that has one copy in each object. Similarly, a function that requires access to a class member without requiring a call to a particular object is also called a static member function.
A static member function of a class can only access static members (variables or functions) of a class.

Further detailed explanations are as follows:

1. First to introduce it is also the most important article: Hide

When we compile multiple files at the same time, all global variables and functions that do not have a static prefix have global visibility. For the understanding of this sentence, I would say for example. We want to compile two source files at the same time, one is A.C and the other is main.c. Here's what's A.C:

char a = ' a '; Global variable

void msg () {printf ("hello\n");}

Here's what's MAIN.C:

int main (void) {

extern char A; extern variable must be declared before use

printf ("%c", a);

(void) msg ();

return 0; }

The running result of the program is:

A Hello

You might ask: Why are global variables A and function msg defined in A.C used in MAIN.C? As mentioned earlier, all global variables and functions that do not have a static prefix have global visibility and other source files can be accessed. In this example, a is a global variable, MSG is a function, and neither has a static prefix, so MAIN.C is visible for additional source files.

If static is added, it is hidden from other source files. For example, before the definition of a and MSG, add STATIC,MAIN.C to see them. With this feature, you can define a function with the same name and a variable of the same name in different files without worrying about naming conflicts. Static can be used as a prefix for functions and variables, and for functions, static is limited to hiding, and for variables, static has the following two functions.

2. The second function of static is to preserve the persistence of variable content

Variables stored in the static data area are initialized at the start of the program and are the only one initialized. A total of two variables are stored in static storage: Global variables and static variables, except that, compared to global variables, static can control the visible range of variables, in the final analysis, static is used to hide them. Although this usage is not common, I would like to cite an example.

#include

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 <=; ++count)

printf ("%d\t\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 function of static is initialized to 0 by default. The global variable also has this property because global variables are also stored in the static data area

In the static data area, all bytes in memory default values are 0x00, sometimes this feature can reduce the workload of the programmer. For example, to initialize a sparse matrix, we can place all the elements in one place 0, and then assign values to elements that are not 0. If it is defined as static, it eliminates the first 0 operation. Another example is to put a character array as a string to use, but also feel each time at the end of the character array to add ' s ' too troublesome. If the string is defined as static, it saves the trouble, because it is already ' the '. Do a little experiment to verify it.

#include

int A;

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 as follows integer:0; string: (Begin) (end)

Finally, the static three effect of a sentence summary. First, the primary function of static is to hide, and second, because static variables are stored in the static storage area, it has a persistence and default value of 0.

4. Summary of functions and variables declared with static

Static declared variables have two characteristics in the C language:

1), the variable will be placed in the program's global store, so that the next call can also maintain the original assignment. This is the difference between a stack variable and a heap variable.

2), variable with static to tell the compiler, itself only within the scope of the variable is visible. This is the difference between it and the global variable.

Tips:
A. If the global variable is accessed only in a single C file, you can modify the variable to a static global variable to reduce the coupling between the modules;
B. If the global variable is accessed only by a single function, the variable can be changed to a static local variable of the function to reduce the coupling between the modules;
C. When designing and using functions that access dynamic global variables, static global variables, and static local variables, you need to consider the re-entry problem;
D. If we need a reentrant function, then we must avoid using the static variable in the function (a function called "Internal memory" function)
The static variable condition must be used in the function: for example, when the return value of a function is a pointer type, it must be the address of the static local variable as the return value, and if it is the auto type, it is returned as the wrong pointer.

The function is static by adding a static to the function. But the meaning of "static" here is not the means of storage, but the scope of the function is confined to this file (so called intrinsic function). The advantage of using intrinsic functions is that different people write different functions without worrying about the functions they define and whether they 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 in order to represent a local variable that still exists after exiting a block. Then, Static has a second meaning in C: the global variables and functions that represent the inability to be accessed by other files. To avoid introducing new keywords, the static keyword is still used to represent this second meaning. Finally, C + + reuses this keyword and gives it a different third meaning from the previous one: the variables and functions that represent any particular object belonging to a class other than this class (the same meaning as 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) According to the storage area, global variables, static global variables and static local variables are stored in the static storage area of memory, local variables are stored in the memory stack area.

(2) by scope, the global variables are valid throughout the project file; a static global variable is only valid within the file that defines it; a static local variable is only valid within the function that defines it, except that the program allocates only one memory, and the variable does not disappear after the function returns, and the local variable is valid within the function that defines it. But the function returns and then fails.

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 that 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. 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. 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, it can be seen that changing the local variable to a static variable changes its storage mode, which changes its life time. Changing a global variable to a static variable changes its scope and limits its scope of use.

(1) The static function is different from the normal function scope. Only in this document. Functions that are used only in the current source file should be described as intrinsic (static) and intrinsic functions should be described and defined in the current source file. For functions that can be used outside of the current source file, it should be stated in a header file that the source file to which the function is to be used is to contain the header file

(2) What is the difference between a static global variable and a normal global variable: the static global variable is initialized only once, preventing it from being referenced in other file units;

(3) What is the difference between static local variable and ordinary local variable: Static local variable is initialized only once, next time according to last result value;
(4) What is the difference between a static function and a normal function: The static function has only one copy in memory, and the normal function maintains a copy of each call.
(5) Global variables and static variables are initialized to 0 by the compiler if they are not manually initialized. The value of the local variable is not known.

5. The static of C + +

The static of C + + is used in two ways: static in process-oriented programming and static in object-oriented programming. The former applies to ordinary variables and functions, and does not involve classes; the latter mainly describes the role of static in classes.

(1), for the static process design

1), Static global variables

Before the global variable, the variable is defined as a static global variable, plus the keyword static. Let's first give an example of a static global variable, as follows:

Example 1

#include <iostream.h>

VOID Fn ();

static int n; Defining static global Variables

void Main ()

{

n=20;

cout<<n<<endl;

FN ();

}

VOID Fn ()

{

n++;

cout<<n<<endl;

}

Static global variables have the following characteristics:

i) the variable allocates memory in the global data area;
II) uninitialized static global variables are automatically initialized by the program to 0 (the value of the automatic variable is random, unless it is explicitly initialized);
III) A static global variable is visible in the entire file that declares it, and is invisible outside the file;

Static variables allocate memory in the global data area, including the static local variables that will be mentioned later. For a complete program, the distribution in memory is as follows:

Code Area

Global Data area

Heap Area

Stack area

The dynamic data generated by new in the general program is stored in the heap area, and the automatic variables inside the function are stored in the stack area. Automatic variables generally free up space as the function exits, and static data (even static local variables inside the function) is stored in the global data area. The data in the global data area does not free up space because of the function's exit. Careful readers may find that the code in Example 1 will

static int n; Defining static global Variables

Switch

int n; Defining Global Variables

The program is still functioning normally. It is true that defining global variables allows for the sharing of variables in files, but there are also the following benefits of defining static global variables:

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

2) variables of the same name can be defined in other files, and no conflict will occur;

You can change the example code above to read as follows:

Example 2

File1

#include <iostream.h>

VOID Fn ();

static int n; Defining static global Variables

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 see that the above code can be compiled separately, but there is an error at run time. Try to

static int n; Defining static global Variables

Switch

int n; Defining Global Variables

Compile and run the program again, carefully understand the difference between global variables and static global variables.

(2), static local variables

Before a local variable, the variable is defined as a static local variable, plus the keyword static. Let's first give an example of a static local variable, as follows:

Example 3

#include <iostream.h>

VOID Fn ();

void Main ()

{

FN ();

FN ();

FN ();

}

VOID Fn ()

{

Static n=10;

cout<<n<<endl;

n++;

}

Typically, a variable is defined in the body of the function that allocates stack memory to the local variable whenever the program runs to the statement. However, as the program exits the function body, the system will retract the stack memory, and the local variables are invalidated accordingly. But sometimes we need to save the values of the variables between the two calls. The usual idea is to define a global variable to implement.  In this way, the variables are no longer part of the function itself, and are no longer only controlled by the functions, which inconvenience the maintenance of the program. Static local variables can solve this problem. Static local variables are saved in the global data area, not in the stack, and each time the value is kept to the next

Detailed description of static keywords in C + +

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.