A summary of the role of static keywords in C + + _c language

Source: Internet
Author: User

1. First and foremost, the first and most important one: hide. (static function, static variable all can)
When you compile multiple files at the same time, all global variables and functions that have no static prefix are globally visible.
For example, Ming. Compile two source files at the same time, one is A.C and the other is main.c.

Copy Code code as follows:

A.c
char a = ' a '; Global variable
void msg ()
{
printf ("hello\n");
}

Copy Code code as follows:

Main.c

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


The results of the program's operation are:
Copy Code code as follows:

A Hello

Why is global variable A and function msg defined in A.C used in MAIN.C? As I said before, all Global variables and functions with no static prefix have global visibility, other source files can also 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 another source file.

IfWith static, the other source files are hidden。 For example inThe definition of A and MSG plus STATIC,MAIN.C won't see them.。 With this feature, you can define a function with the same name and a variable of the same name in a different file without having to worry aboutNaming conflicts。 Static can be used as a prefix for functions and variables,For functions, the static effect is limited to the hidden.

the second role of 2.static is to keep variable content persistent. (Memory function and global lifetime in a static variable)
stored instatic data areaThe variable will be in theInitialization is complete when the program is first runAlsoOnly one initialization。 A total of two variables are stored in theStatic storage: Global variables and static variables, but compared with global variables,Static can control the visible range of variables, the static is still used to hide. 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 the scope is still the same as the automatic variable and can only be used within the function that defines the variable. After exiting the function, it cannot be used, although it continues to exist.

Program Examples:

Copy Code code as follows:

#include <stdio.h>
int fun () {
static int count = 10; The first time you 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, only to do the operation of 1, and in the same way before static invention, you can only use global variables to achieve the same function:
}
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 results of the program's operation are:
Copy Code code as follows:

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: changing the local variable to a static variable changes its storage mode, which changes its lifetime. Changing the global variable to a static variable changes its scope and limits its use. So the static this specifier plays a different role in different places.

The third effect of 3.static is to initialize the default to 0 (static variable)
In fact , global variables also have this attribute, because global variables are also stored in the static data area. In the static data area, all the byte defaults in memory are 0x00, which can sometimes reduce the programmer's workload. For example , to initialize a sparse matrix, we can place all the elements in one place 0, and then assign a few elements that are not 0. If defined as static, it eliminates the operation of starting with 0. Another example is to use a character array as a string, but also feel that each time at the end of the character array Plus ' "; too much trouble. If the string is defined as static, it saves the trouble, because there is a ' yes ', and a little experiment to prove it.

Copy Code code as follows:

#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 results of the program's operation are:
Copy Code code as follows:

integer:0; String: (Begin) (end)

Finally, the static three function to do a summary of the sentence.The main function of the static first is to hide, and second, because the static variable is stored in the quiescent store, it has a persistence and default value of 0.

The Fourth role of 4.static: class member declaration static in C + + (some places overlap with the above action)
When a static variable or function is declared in a class, the scope operator is used when initializing to indicate the class to which it belongs, so the static data member is a member of the class, not a member of the object, and the following effects occur:

(1) A static member function of a class is an object that belongs to an entire class, not a class, so it has no this pointer, which causes it to access only static data and static member functions of the class.

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

(3) because the static member is declared in the class, the operation is outside, so to its address operation, is somewhat special, the variable address is pointing to its data type pointer, the function address type is a "nonmember function pointer".

(4) Since the static member function does not have the this pointer, it is almost equivalent to the nonmember function, resulting in an unexpected benefit: becoming a callback function that allows us to combine C + + and c-based X W Indow Systems, It is also successfully applied to the thread function. (This one has never been met)

(5) Static does not add to the time and space overhead of the program, but she also shortens the access time of subclasses to static members of the parent class and saves the memory space of the child classes.

(6) Static data members precede the < definition or description > with the keyword static.

(7) static data members are stored statically, so it must be initialized. (manual initialization of the programmer, otherwise compile-time will not normally error, but when link will report errors)

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

Initialization is done outside the class body, without the preceding static, so as not to be confused with a general static variable or object;
The private,public of the access rights control character of the member is not added when initializing;
The scope operator is used when initializing to indicate the class to which it belongs;
So we get the format of the static data member initialization:
< data type >< class name >::< static data member name >=< value >

(9) To prevent the parent class from being affected, you can define a subclass with the same static variable as the parent class to mask the effects of the parent class. Here's one thing to note: we say that static members are shared by the parent class and subclass, but do we have a duplicate definition of static members that will not cause errors? No, our compiler uses a neat trick: name-mangling to generate a unique flag .

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.