Summary of the static keywords in C/C ++

Source: Internet
Author: User

1. first introduce the first and most important one: Hide. (Static function, static variable)

When multiple files are compiled at the same time, all global variables and functions without the static prefix are globally visible.
For example. Compile two source files, a. c and main. c.

//a.cchar a = 'A';               // global variablevoid msg(){     printf("Hello\n");}

 

//main.cint main(){     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

 

 

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, static can only be used for hiding.

 

2. The second role of static is to keep the variable content persistent. (Memory and global survival in static variables)

 

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 method is not common

PS: If it is defined as a static local variable in the function, its lifetime is the entire source program, but its scope is still the same as that of the 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.

 

Program example:

# Include <stdio. h> int fun () {static int count = 10; // when you first enter this function, variable a is initialized to 10! And then subtract 1, and then each time you enter the function, a return count --; // will not be initialized again, and only perform the operation of auto minus 1; Before the static invention, to achieve the same function, you can only use the global variable:} 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

 

 

 

 

 

 

 

 

 

 

 

 --- Based on the above two points, we can draw a conclusion: After changing a local variable to a static variable, it changes its storage method, namelyChanged its survival.. After changing a global variable to a static variable, it changes its scope,Limits its scope of use. Therefore, the description of static plays different roles in different places.

 

3. The third role of static is to initialize 0 (static variable) by default)

 

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 to verify it.

 

#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 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. The fourth role of static: class member declaration in C ++ static (some places overlap with the above)

When declaring static variables or functions in a class, the scope operator is used to indicate its class during initialization. Therefore, static data members are class members rather than object members, in this way, the following functions are available:

(1) The static member function of the class belongs to the entire class rather than the Class Object. Therefore, it does not have the this pointer, which leads to the ability to parse static data and static member functions of the class only.

(2) static member functions cannot be defined as virtual functions.

(3) because static members are declared in the class and operated outside of the class, it is somewhat special to perform the address fetch operation on them. The variable address is a pointer to its data type, the function address type is a "nonmember function pointer ".

(4) because the static member function does not have the this pointer, it is almost equivalent to the nonmember function, and the result produces an unexpected benefit: To become a callback function, this allows us to combine C ++ and C-based x w indow systems, and successfully apply them to thread functions. (This one never met)

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

(6) Add the keyword "static" before <definition or description> to the static data member.

(7) static data members are stored statically, so they must be initialized. (Manually initialize the program; otherwise, no error is reported during compilation, but an error is reported during Link)

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

Initialization is performed in the external class without static before, so as to avoid confusion with general static variables or objects;
During initialization, the access permission control characters private and public of the member are not added;
During initialization, the scope operator is used to indicate the class to which it belongs;
So we can get the format of static data member initialization:
<Data type> <class name >:< static data member name >=< value>

(9) to prevent the influence of the parent class, you can define a static variable of the same as the parent class in the subclass to avoid the influence of the parent class. Note the following:We say that static members are shared by the parent class and subclass, but we have repeatedly defined static members. Will this cause an error? No, our compiler uses a wonderful method: name-mangling is used to generate a unique flag..

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.