Static usage Summary

Source: Internet
Author: User

Static usage Summary

Statickeyword is a keyword that exists in C and C ++. It mainly has three usage methods, the first two of which are only used in C, the third method is used in C ++. (The detailed operations in C and C ++ are different. This document uses C ++ as the standard ).
(1) local static variables
(2) external static variables/functions
(3) static data member/member functions
The following three usage methods and precautions are described respectively:

I. Local static variables
In C/C ++, local variables can be divided into three types: auto, static, and register.
(<C language programming (second edition)> tan haoqiang, pp. 174-175)
Compared with the auto-type (common) local variable, the static local variable has three differences.
1. Different Storage space allocations
The auto type is allocated to the stack and belongs to the dynamic storage class, occupying the dynamic storage space. After the function call is completed, the auto type is automatically released, while the static type is allocated to the static storage area, the program is not released during the entire execution period. the scope is the same, but the lifetime is different.
2. Static local variables initialize at the first execution of the module, and only perform operations once.
3. for local static variables, if no initial value is assigned, the initial value 0 or null characters are automatically assigned during the compilation period, while the initial values of the auto type are uncertain. (except for class objects in C ++, if the class object instance is not initialized, the default constructor is automatically called, whether it is static or not)

Features: "Memory" of static local variables and "Global" of lifetime"
The so-called "Memory" refers to the value of the first function call exit when the second function call enters.
Demo Example 1
# Include <iostream>

Using namespace STD;

Void staticlocalvar ()
{
Static int A = 0; // Initialization is performed during the execution period. Initialization is not performed for the next call.
Cout <"A =" <A <Endl;
++;
}

Int main ()
{
Staticlocalvar (); // the first call, output a = 0
Staticlocalvar (); // The second call, remembering the value at the first exit, output a = 1
Return 0;
}

Application:
Use "Memory" to record the number of function calls (Example 1)
Improve the problem of "return a pointer/reference to a local object" by using global survival. the problem with the local object is that the function exits and the lifetime ends ,. use static to prolong the lifetime of a variable.
Demo Example 2:
// Ip address to string format
// Used in Ethernet frame and IP header analysis
Const char * iptostr (uint32 ipaddr)
{
Static char strbuff [16]; // static local variable, used to return valid addresses
Const unsigned char * PChIP = (const unsigned char *) & ipaddr;
Sprintf (strbuff, "% u. % u. % u", PChIP [0], PChIP [1], PChIP [2], PChIP [3]);
Return strbuff;
}

Note:
1. "Memory", the most important thing for running a program is that it can be repeated, and the "Memory" of static variables damages such repeatability, resulting in different runtime results may be different.
2. global and uniqueness of "Lifetime. the storage space of common local variables is allocated to the stack. Therefore, the allocated space may be different each time a function is called. Static has the global uniqueness feature, all point to the same memory, which leads to a very important problem-re-import is not allowed !!!
In this way, pay special attention to this issue in multi-threaded or recursive programming.
(For examples of non-reentrant properties, refer to page 103-105 of <valid tive C ++ (2nd)> (photoprinting)
The following is an example of Program 2, which analyzes the security of multiple threads. (to facilitate the description, mark the line number)
① Const char * iptostr (uint32 ipaddr)
② {
③ Static char strbuff [16]; // static local variable, used to return valid addresses
④ Const unsigned char * PChIP = (const unsigned char *) & ipaddr;
⑤ Sprintf (strbuff, "% u. % u. % u", PChIP [0], PChIP [1], PChIP [2], PChIP [3]);
⑥ Return strbuff;
7}
If two threads a and B need to call the iptostr () function during running, convert the 32-bit IP address to a string in the 10th notation. now, a obtains the running opportunity and runs iptostr (). The number of incoming records is 0x0b090a0a. the pointer storage content that should be returned after the sequential operation is: "10.10.9.11". At this time, if the operation permission is lost, it is scheduled to run on line B. The number of bytes input by line B is 0xa8a8a8c0, and the content of the static storage area is 192.168.168.168. when it is scheduled to run on a again, it will continue to run from 6th. Because of the global uniqueness of strbuff, the content has been washed out by line B. At this time, the returned string is the string 192.168.168.168, not the string 10.10.9.11.

Ii. External static variables/functions
Static in C has another meaning: it is used to indicate global variables and functions that cannot be asked by other files ., However, to restrict the scope of global variables/functions, add static before a function or variable 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 ). Note that, whether static or not, external (global) variables are stored in the static storage area and the lifetime is global. at this time, static only acts as a scope restriction and limits the scope within this module (file.
The advantage of using internal functions is that when different people write different functions, you don't have to worry about custom functions and whether they will have the same name as the functions in other files.
Demo Example 3:
 
// File1.cpp

Static int Vara;
Int varb;
Extern void FUNA ()
{
......
}

Static void funb ()
{
......
}

// File2.cpp

Extern int varb; // use the global variable defined in file1.cpp
Extern int Vara; // error! Vara is static and cannot be used in other files.
Extern vod funa (); // use the function defined in file1.cpp
Extern void funb (); // error! You cannot use the static function in the file1.cpp file.

 

Iii. static data member/member functions (C ++ exclusive)
C ++ re-uses this keyword and gives it a third meaning different from the previous one: it indicates that it belongs to a class rather than the variables and functions of any specific object of this class. this is the biggest difference from a common member function and its application. For example, how many classes are generated by counting objects of a class, you can use static data members. static does not limit the scope or extend the lifetime, but indicates the uniqueness of variables/functions in this class. this is also the meaning of "belong to a class rather than belong to this class regardless of the specific object variables and functions. because it is unique for the entire class, it cannot belong to an instance object. (For static data members, whether a member function is static or not, there is only one copy in the memory. When calling a common member function, this pointer must be passed in. When calling a static member function, no this pointer .)
See example 4 (Copyright c ++ (2nd)> (copyright) page 1)
Class enemytarget {
Public:
Enemytarget () {++ numtargets ;}
Enemytarget (const enemytarget &) {++ numtargets ;}
~ Enemytarget () {-- numtargets ;}
Static size_t numberoftargets () {return numtargets ;}
Bool destroy (); // returns success of attempt to destroy enemytarget object
PRIVATE:
Static size_t numtargets; // object counter
};
// Class statics must be defined outside the class;
// Initialization is to 0 by default
Size_t enemytarget: numtargets;

In this example, the static data member numtargets is used to count the number of generated objects.
In addition, when designing multi-threaded operations, because the thread function pthread_create () in the POSIX Library requires global processing, common member functions cannot be directly used as thread functions, consider using static member functions as thread functions.

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.