Static usage Summary

Source: Internet
Author: User
The static keyword is a keyword that exists in both C and C ++. It mainly has three usage methods. The first two are only used in C, the third method is used in C ++. (The detailed operations in C and C ++ vary. This document uses C ++ as the standard ). (1) local static variables (2) external static variables/functions (3) the following three usage methods and precautions for static data member/member functions: 1. Local static variables are in C/C ++, and local variables can be divided into three types of auto according to the storage format, static, register (<C Language Program Design (version 2)> tan haoqiang, page 174-175) compared with the auto-type (common) local variables, static local variables have three differences. different auto types of Bucket allocation are allocated on the stack. They belong to the dynamic storage class and occupy the space in the dynamic storage zone. The function is automatically released after the function call is completed, while static storage is allocated in the static storage zone, the program is not released during the entire running period. they have the same scope but different lifetime. 2. static local variables initialize at the first run of the module and operate only once. 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, regardless of whether it is static or not.) features: static local variables have a "Memory" and a "global" of survival. The so-called "Memory" refers to the two function calls, when the second call enters, the value of the first call exit is retained. sample program I # include <iostream> using namespace STD; void staticlocalvar () {static int A = 0; // It is initialized at runtime and will be called again next time, do not initialize cout <"A =" <A <Endl; ++ A;} int main () {staticlocalvar (); // the first call, output A = 0 staticlocalvar (); // The second call, remembering the value of the first exit, and outputting A = 1 return 0;} application: using "Memory ", record the number of function calls (Example 1) Improve the problem of "return a pointer/reference to a local object" by taking advantage of the "global" of the lifetime. the problem with the local object is that the function exits and the lifetime ends ,. use static to prolong the lifetime of a variable. example 2: // ip add RESS to string format // used in Ethernet frame and IP header analysisconst char * iptostr (uint32 ipaddr) {static char strbuff [16]; // static local variable, valid const unsigned char * PChIP = (const unsigned char *) & ipaddr; sprintf (strbuff, "% u. % u. % u. % u ", PChIP [0], PChIP [1], PChIP [2], PChIP [3]); Return strbuff;} Note: 1. "Memory", a very important part of the program running is repeatability, and the "Memory" of static variables damages this repeatability, resulting in different time points to run results may be different. 2. global and uniqueness of "Lifetime. common Loc The storage space of the Al variable is allocated to the stack. Therefore, each time a function is called, the allocated space may be different. 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. (Examples of non-reentrant properties can be found in <effective C ++ (2nd)> (photoprinting) page 103-105). For example, Program 2 is used to analyze the insecure performance of multithreading. (For easy description, mark the row number) ① const char * iptostr (uint32 ipaddr) ② {③ static char strbuff [16]; // static local variable, valid return address ④ const unsigned char * PChIP = (const unsigned char *) & ipaddr; ⑤ sprintf (strbuff, "% u. % u. % u. % u ", PChIP [0], PChIP [1], PChIP [2], PChIP [3]); ⑥ return strbuff; 7} assume there are two threads, B needs to call the iptostr () function during running The bitwise IP address is converted into a string in decimal order. now a gets the execution opportunity and runs iptostr (). The input parameter is 0x0b090a0a. After the execution is complete, the returned pointer storage area is: "10.10.9.11". When the execution ends, if the execution permission is lost, the task is scheduled to run in line B. The parameter passed in line B is 0xa8a8c0 and executed to 7. The content in the static storage area is 192.168.168.168. when it is scheduled again to a for execution, it continues from 6th to 6th. Due to the global uniqueness of strbuff, the content has been washed out by line B. In this case, the returned string is the string 192.168.168.168, not the string 10.10.9.11. 2. External static variables/functions static in C has the second meaning: Used to indicate global variables and functions that cannot be accessed 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 applies to the scope, and the scope is limited 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 your own defined functions and whether they will have the same name as the functions in other files. Example 3: // file1.cppstatic int Vara; int varb; extern void FUNA (){......} Static void funb (){......} // File2.cppextern int varb; // use the global variable extern int Vara defined in file1.cpp; // error! Vara is static and cannot use extern vod funa () in other files; // use the function extern void funb () defined in file1.cpp; // error! You cannot use the static function in the file1.cpp file. 3. The static data member/member function (C ++ exclusive) C ++ reuses this keyword and gives it a third meaning different from the previous one: variables and functions that belong to a class rather than any specific objects of this class. this is the biggest difference between a function and a common member function and its application. For example, when counting an object of a class, counting the number of instances of the class is generated, 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 "variables and functions that belong to a class rather than any specific objects of this class. because it is unique for the entire class, it cannot belong to an instance object. (For static data members, whether the 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 program 4 (<Effect Ive C ++ (2nd)> (photocopy) page 59th) Class enemytarget {public: enemytarget () {++ numtargets;} enemytarget (const enemytarget &) {++ numtargets ;} ~ Enemytarget () {-- numtargets;} static size_t evaluate () {return numtargets;} bool destroy (); // returns success of attempt to destroy enemytarget objectprivate: static size_t numtargets; // object counter}; // class statics must be defined outside the class; // Initialization is to 0 by defaultsize_t enemytarget: numtargets; in this example, the static data member numtargets is used to count the number of generated objects. in addition, because the thread function pthread_create () in the POSIX database requires a global mechanism when designing multi-threaded operations, common member functions cannot be directly used as thread functions, you can use the static member function as a thread function.

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.