Explanation of static keywords in C/C ++

Source: Internet
Author: User

Explanation of static keywords in C/C ++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.

 

The above is transferred from:

 

Http://www.cnblogs.com/yc_sunniwell/archive/2010/07/14/1777441.html

 

----------------------------------------------------------- Split line -------------------------------------------------------------------------

 

 

C-language programs can be viewed as composed of a series of external objects, which may be variables or functions. Internal variables refer to the function parameters and variables defined within the function. External variables are defined outside functions, so they can be used in many functions. Since the C language does not allow defining other functions in a function, the function itself can only be "external ".
C language code is organized in files. In all source files of a source program, an external variable or function can be defined only once in a file, other files can access it through the extern Declaration (the source file defining the external variable or function can also contain the extern Declaration for the external variable ).
Static storage can restrict variables or functions to static storage. If you use static to restrict external variables and functions, You can restrict the scope of the object to the rest of the compiled source file. You can use static to restrict external objects to hide them. Therefore, static variables or functions do not conflict with the same name in other files in the same program. If you use static to limit the internal variable, the variable will have memory from the beginning of the program and will not be allocated and disappear as the function calls and exits.
Benefits of using static functions in C Language:

  1. Static functions are automatically allocated to a used storage area until they exit the application instance. This avoids the pressure on the stack to exit the stack when calling the function, which is much faster.
  2. The keyword "static" is "static" in Chinese. Therefore, internal functions are also called static functions. However, the meaning of "static" here is not the storage method, but the scope of the function is limited to this file. The advantage of using internal functions is that when different people write different functions, you don't have to worry about whether your own defined functions will have the same name as the functions in other files, because the same name does not matter.

Static semantics in C Language
1. static variables:
1). Local
A. Static local variables are defined in the function. The lifetime is the entire source program, but the scope is the same as that of automatic variables. They can only be used in the function that defines the variable. After exiting the function, although the variable still exists, it cannot be used.
B. 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.
2). Global
Global variables are static storage, and static global variables are also static storage. But their scope: the scope of non-static global variables is the entire source program (multiple source files can be used together), while static global variables limit their 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.
2. static function (also called internal function)
It can only be called by functions in this file, but not by functions in other files of the same program. Different from general non-static functions (external functions)
Static can be used to modify variables or functions in c.
Let's first look at the time when it is used to modify variables. Variables in c can be divided into global data areas, stacks, and stacks. In fact, the stack we usually call is a stack that does not contain a pair. Don't confuse it.
Int;
Main ()
{
Int B;
Int c * = (int *) malloc (sizeof (int ));
}
A is a global variable, B is a stack variable, and c is a stack variable.
Static modification to the global variable can be considered as limiting that the variable can only be referenced in this file. Some programs are composed of many. c files. Variables can be referenced by each other. However, after static modification, the variable can only be referenced by functions in this file.
Static modification of stack variables can be considered to extend the life cycle of stack variables to the end of program execution. In general, the life cycle of stack variables is managed by OS. During the rollback process, the life of stack variables ends. However, after static modification, the variables are not stored in the stack, but stored together with global variables. At the same time, it cannot be used after the function that defines it is left blank. However, if you call the function that defines it again, it can continue to be used and save the value left after the previous call.
Static Function Modification is similar to global variable modification. It can only be called by functions in this file, but cannot be called by functions in other files of the same program.
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.

Question: Static understanding

For static variables, select the correct content for all the following statements:

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 need to consider re-import;

D. The static global variable is too large, which may cause stack overflow.

Answer and analysis:

For A, B: according to the description in the overview section B), we know that A and B are correct.

For C: according to the description in the overview section of this article a), we know that C is correct (the so-called function re-entry problem is described in detail below ).

For D: static variables are placed in the global data zone of the program, rather than allocated in the stack, so it is impossible to cause stack overflow. D is wrong.

Therefore, the answer is A, B, and C.

Problem: Non-reentrant Functions

I have designed a function such as the next function. I was reminded of a bug during code check because this function cannot be reentrant. Why?

Unsigned int sum_int (unsigned int base)
{
Unsigned int index;
Static unsigned int sum = 0; // note that it is of the static type.
For (index = 1; index <= base; index ++)
{
Sum + = index;
}
Return sum;
}

Answer and analysis:

The so-called function is reentrant (or predictable), that is, the same output should be generated as long as the input data is the same.
This function is unpredictable because it uses static variables. Because of the characteristics of static variables, such a function is called a function with the "internal memory" function. Therefore, if we need a reentrant function, we must avoid using static variables in the function. The principle of using static variables in this function is that we do not need to use them as much as possible.
It is very easy to change the above function to a reentrant function. As long as the static keyword in the declared sum variable is removed, the variable sum is changed to an auto type variable, A function is a reentrant function.
Of course, in some cases, static variables must be used in functions. For example, when a function returns a pointer type, the address of a static local variable must be used as the return value, if it is of the auto type, an error pointer is returned.

1. static variable

The type description of static variables is static. Static variables belong to static storage, but not necessarily static variables. For example, an external variable is a static storage method, but not necessarily a static variable. It must be defined by the static variable before it can become a static external variable or a static global variable.

2. Static local variables
Static local variables are stored in static mode and have the following features:
(1) the lifetime of a static local variable is defined as the entire source program in the function, but its scope is still the same as that of an automatic variable. It can only be used within the function that defines the variable. After exiting the function, although the variable still exists, it cannot be used.

(2) An initial value such as an array can 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.
(3) 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 also achieve the above purpose, global variables sometimes cause unexpected side effects, so it is best to use local static variables.

3. 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.

4. static functions .....

Internal and external functions

When a source program is composed of multiple source files, the C language divides the function into internal functions and external functions based on whether the function can be called by functions in other source files.
1 internal function (also known as static function)
A function defined in a source file can only be called by functions in this file, but cannot be called by functions in other files of the same program. This function is called an internal function.
To define an internal function, you only need to add a "static" keyword before the function type, as shown below:
Static function name (function parameter table)
{......}
The keyword "static" is "static" in Chinese. Therefore, internal functions are also called static functions. However, the meaning of "static" here is not the storage method, but the scope of the function is limited to this file.
The advantage of using internal functions is that when different people write different functions, you don't have to worry about whether your own defined functions will have the same name as the functions in other files, because the same name does not matter.

2. External Functions
External Function Definition: when defining a function, if the keyword "static" is not added or the keyword "extern" is appended, this function is an external function:
[Extern] function name (function parameter table)
{......}
When calling an external function, you need to describe it:
[Extern] function name of the function type (parameter type table) [, function name 2 (parameter type table 2)…];

[Case] external function application.
(1) file mainf. c
Main ()
{Extern void input (...), Process (...), Output (...);
Input (...); Process (...); Output (...);
}

(2) file subf1.c
......
Extern void input (......) /* Define external functions */
{......}
(3) file subf2.c
......
Extern void process (......) /* Define external functions */
{......}
(4) file subf3.c
......
Extern void output (......) /* Define external functions */
{......}

 

Http://blog.csdn.net/zhongjiekangping/archive/2010/06/01/5639774.aspx

Related Article

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.