Summary of the static keyword in C and C++

  • 2020-04-02 01:32:50
  • OfStack

1. Let's start with the first and most important one: hiding. (static function, static variable)
When multiple files are compiled simultaneously, all global variables and functions that are not prefixed with static are globally visible.
Let me give you an example. Compile two source files simultaneously, one a.c and the other main.c.


//a.c
char a = 'A';               // global variable
void msg()
{
     printf("Hellon");
}


//main.c
int main()
{
     extern char a;       // extern variable must be declared before use
     printf("%c ", a);
     (void)msg();
     return 0;
}

The result of running the program is:

A Hello

Why can the global variables a and the function MSG defined in a.c be used in main.c? As mentioned earlier, all global variables and functions that are not prefixed with static are globally visible and accessible to other source files. In this example, a is a global variable and MSG is a function, and both are not prefixed with static, so they are visible to the other source main.c.

If you add static, it will be hidden from other source files. For example, if you put static before the definition of a and MSG, main.c will not see them. This feature allows you to define functions and variables with the same name in different files without worrying about naming conflicts. Static can be used as a prefix for functions and variables. For functions, static is only used to hide.

The second purpose of static is to keep the contents of a variable persistent. Memory and global lifetime in static variables
Variables stored in static data areas are initialized the first and only time the program starts running. There are two kinds of variables stored in the static storage area: global variables and static variables. However, compared with global variables, static variables can control the visibility of variables. Although this usage is unusual

PS: if defined as a static local variable in a function, its lifetime is the entire source program, but its scope is still the same as that of an automatic variable, which can only be used in the function where the variable is defined. After exiting the function, the variable cannot be used, although it continues to exist.

Examples of procedures:


 # include <stdio.h>
int fun(){
    static int count = 10;       //On the first entry into this function, the variable a is initialized to 10 factorial. And then we're going to subtract 1, and we're going to enter this function every time. A
    return count--;              //It's not initialized again, it's just subtracted 1; Before the static invention, the only way to achieve the same functionality is to use the global variable: & PI; & have spent & have spent
}
int count = 1;
int main(void)
{
     printf("globalttlocal staticn");
     for(; count <= 10; ++count)
               printf("%dtt%dn", count, fun());
     return 0;
}

The result of running 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

One conclusion can be drawn from the above two points: changing a local variable to a static variable changes the way it is stored, that is, its lifetime. Changing a global variable to a static variable changes its scope and limits its use. So the static specifier does different things in different places.

The third function of static is to initialize it as 0 (static) by default.
Global variables also have this property because they are also stored in static data areas. In static data areas, the default value of all bytes in memory is 0x00, which can sometimes reduce the programmer's workload. For example, to initialize a sparse matrix, we can set all the elements to 0 one by one, and then assign several elements that are not 0. If you define it as static, you save the initial zero. Another example is to use an array of characters as a string, but feel like adding '\0' to the end of the array every time; Too much trouble. If you define the string as static, you save the trouble because it's already '\0'; You might as well do a little experiment to verify that.


 # include <stdio.h>
int a;
int main()
{
     int i;
     static char str[10];
     printf("integer: %d; string: (begin)%s(end)", a, str);
     return 0;
}

The result of running the program is:

integer: 0; string: (begin) (end)

Finally, the static of the three effects of a sentence summary. First, the main function of static is hiding, and second, because static variables are stored in static storage, they have persistence and a default value of 0.

4. The fourth function of static: class member in C++ declares static (some places overlap with the above function)
When declaring a static variable or function in a class, the scope operator is used to indicate its class membership when initializing it. Therefore, the static data member is a member of the class, not a member of the object. Thus, the following functions appear:

(1) the static member function of the class is an object belonging to the whole class instead of the class, so it does not have this pointer, which causes it to only access the static data and static member function of the class.          

(2) a static member function cannot be defined as a virtual function.          

(3) because of the static member declaration in the class, the operation in its outside, so to its address operation, more or less some special, the variable address is a pointer to its data type, the function address type is a "nonmember function pointer."

(4) since the static member function does not have this pointer, it is almost the same as the nonmember function. The result is an unexpected benefit: it is a callback function, which enables us to combine C++ and c-based X W indow system, and it is also successfully applied to the thread function.   (I haven't met this one)    

(5)static does not increase the space-time overhead of the program. On the contrary, it also shortens the access time of the subclass to the static member of the parent class and saves the memory space of the subclass.          

(6) the static data member is in < Definition or description > Is preceded by the keyword static.          

(7) the static data member is statically stored, so it must be initialized.   (the programmer initializes it manually, otherwise it won't normally report an error at compile time, but it will report an error at Link.)          

(8) static member initialization is different from general data member initialization:

Initialization takes place outside of the class without adding static to avoid confusion with general static variables or objects.
When initializing, do not add the member's access control characters private, public, etc.;              
The scope operator is used to indicate the class to which it belongs.
Therefore, we get the format of static data member initialization:
< The data type > < The name of the class > : : < Static data member names > = < value >

(9) in order to prevent the influence of the parent class, a static variable that is the same as the parent class can be defined in the subclass to shield the influence of the parent class. Here's one thing to note: We say that static members are Shared by parent and child classes, but we have repeatedly defined the static members, will that cause an error? No, our compiler USES a clever technique called name-mangling to generate unique flags .


Related articles: