Summary of static keyword functions in C + +

Source: Internet
Author: User
Tags visibility

1. The first and most important article is to introduce it: hide . (static function, static variable all available)

When multiple files are compiled at the same time, all global variables and functions that do not have a static prefix have global visibility.
For example, it is clear. Compile two source files at the same time, one is A.C and the other is main.c.

//A.CCharA ='A';//global variablevoidmsg () {printf ("hello\n");} //main.c intMain () {extern CharA//extern variable must be declared before useprintf"%c", a); (void) msg (); return 0;}

The running result of the program is:

A Hello

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.

the second function of 2.static is to keep the variable content persistent . (Memory function and global lifetime in static variables)

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

PS: If defined within a function as a static local variable, its lifetime is the entire source program, but its scope is still the same as the automatic variable, which can only be used within the function that defines the variable. After exiting the function, it cannot be used even though the variable continues to exist.

Examples of programs:

# include <stdio.h>intFun () {Static intCount =Ten;//The first time you enter this function, the variable A is initialized to 10! And then subtract 1, and each time you enter the function, a    returncount--;//Will not be initialized again, only the operation of the self minus 1, before the static invention, to achieve the same function, you can only use global variables: } intCount =1; intMainvoid) {printf ("global\t\tlocal static\n");  for(; Count <=Ten; ++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

7 |

10 1

---Based on the above two points can be drawn to a conclusion: the change of the local variable to a static variable is changed its storage mode, which changes its lifetime. Changing a global variable to a static variable changes its scope and limits its scope of use. So the function of the static descriptor is different in different places.

The third function of 3.static is to initialize the default to 0 (static variable)

In fact, global variables also have 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 ' + '; too troublesome. If the string is defined as static, it saves the trouble, because there is a ' s '; try to do a little experiment to verify it.

intint  main () {     int  i;      Static Char str[];     printf ("integer:%d; String: (begin)%s (end)", A, str);      return 0 ;}

The running result of the program is:

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.

the fourth function of 4.static: class member declarations in C + + static(some places overlap with the above functions)

When you declare a static variable or function in a class, the initialization uses the scope operator to indicate which class it belongs to, so that the static data member is a member of the class and not a member of the object, so the following effect occurs:

(1) A static member function of a class is an object of the entire class rather than a class, so it does not have the this pointer, which causes it to access only the static data and static member functions of the class .

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

(3) because the static member is declared in the class, the operation is outside, so it takes the address operation, it is somewhat 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 identical to the nonmember function, resulting in an unexpected benefit: being a callback function allows us to combine C + + and c-based X W Indow Systems, It is also successfully applied to the thread function. (This one has not been met)

(5) Static does not increase the space-time overhead of the program, but she also shortens the subclass's access time to the static members of the parent class, saving the memory space of the child class.

(6) static data members in the < definition or description > before adding the keyword static.

(7) A static data member is stored statically, so it must be initialized. (The programmer is initialized manually, otherwise it will not be reported at compile time, but the error is quoted on link)

(8) Static member initialization differs from general data member initialization:

Initialization is performed outside of the class body, and the front is not static, so as not to be confused with the general static variables or objects;
Initialization without the access control of the member Private,public and so on;
The scope operator is used when initializing to indicate the class to which it belongs;
So we derive the format of the static data member initialization:
< data type >< class name >::< static data member name >=< value >

(9) to prevent the effect of the parent class, you can define a static variable in the subclass that is the same as the parent class to mask the effect of the parent class. Here's one thing to note: we say that static members are shared by the parent and subclass, but we have statically defined static members, does that cause errors? No, our compiler uses a neat trick: name-mangling is used to generate unique flags.

Summary of static keyword functions in C + +

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.