The meaning of static and its difference in C + + __c++

Source: Internet
Author: User
Tags string format
The static keyword is a keyword that exists in C and C + +.
There are three ways to use it, the first two of which are used only in the C language,
The third type is used in C + + (the c,c++ is different in detail, this article is based on C + +).
(1) Local static variables
(2) External static variables/functions
(3) static data member/member function

The following three types of usage and precautions are explained separately


one, local static variables


In C + +, local variables can be divided into three types of auto, static, register and auto type (ordinary) local variables, static local variables are three different.
1. Different storage space allocation
The auto type is distributed on the stack, belongs to the dynamic storage category, occupies the dynamic storage space, the function call is released automatically, and the static is allocated in the quiescent storage area, and is not released during the whole running of the program. The scope of the two is the same, but the lifetime is different.
2. Static local variables in the module in theInitialize at first run time and operate only once
3. For local static variables, if the initial value is not assigned, the compile period will automatically assign an initial value of 0 or a blank character, and the initial value of the auto type is indeterminate. (For class object exceptions in C + +, the default constructor is automatically invoked if the object instance of class is not initialized, regardless of whether it is a static type)
features: "Memory" and "global" lifetime of static local variables
The term "memory" means the value of the first call to exit when the second call comes in, when the function is called two times.
Sample program One[CPP]View Plain copy print?   #include <iostream> using namespace std; void Staticloc () {static int a = 0; initialized once at runtime, not initialized when next call cout << "a =" << a << E       Ndl   ++a;      int main () {staticloc ();     First call, Output a = 0 staticloc ();   The second call, memory of the first exit when the value, return 0; }/* A = 0 A = 1 * apply:
Use "Memory" to record the number of function calls (sample program one)
Make use of the "global" of the lifetime, improve "return a pointer/reference to a"
Object "problem. The problem with the local object is to exit the function, which is the end of the lifetime. Use static to extend the lifetime of a variable.
Example program two:[CPP]View Plain copy print?       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 address 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; ⑦} assumes that there are now two threads A, the B run period will need to call the Iptostr () function, the 32-bit IP address to the point 10 into the string form. Now a first obtains the execution opportunity, executes IPTOSTR (), the incoming parameter is 0x0b090a0a,
The pointer store content that should be returned after sequential execution is: "10.10.9.11", now executes to ⑥, loses execution right, dispatches to B thread execution, the parameter that B thread passes is 0xa8a8a8c0,

Execution to ⑦, the contents of the static storage area is 192.168.168.168. When the dispatch to a executes, continues from the ⑥, because the Strbuff's global uniqueness, the content has been flushed by the B thread, at this time will return is the 192.168.168.168 string, is no longer the 10.10.9.11 string.


second, external static variables/functions


The static in C has a second meaning:used to represent global variables and functions that cannot be accessed by other files。 But in order to limit the scope of global variables/functions, a function or variable is statically added before the function becomes a static function. But the meaning of "static" here is not how it is stored,It means that the scope of the function is limited to this file(so also called internal functions). Note that at this point, for external (global) variables, regardless of whether there is a static limit, its storage area is in the static storage area, the lifetime is global.the static at this point is only a function of the domain restriction, which limits the scope within this module (file).
The benefits of using intrinsic functions are:when different people write different functions, they don't have to worry about the functions they define, whether they have the same name as the functions in other files
Sample program Three:[CPP]View Plain copy print?   file1.cpp static int VarA;   int Varb;   extern void Funa () {...}   static void Funb () {...} file2.cpp extern int Varb; Use the global variable extern int VarA defined in file1.cpp; Error! Vara is a static type and cannot be used in other files using the extern VOD Funa (); Use the function defined in file1.cpp to extern void Funb (); Error! Cannot use static function in File1.cpp file

third, static data member/member function (c + + specific)


C + + reuses this keyword and gives it a third meaning that differs from the previous one:variables and functions that represent any particular object belonging to a class other than this class. This is the biggest difference from the ordinary member function, but also its application, for example, when counting the objects of a class, the count generates a number of instances of the class, you can use the static data members. In this case, static is neither a scoped nor an extension lifetime, but rather a indication of the uniqueness of the variable/function in this class. This is also the meaning of "variables and functions that belong to a class and not to any particular object of this class." Because it is unique to the entire class, it is not possible to belong to an instance object. (for static data members, whether a member function is static or not, there is only one copy in memory, and a normal member function call is required to pass in the this pointer,when a static member function is called, there is no this pointer, only the static member variable of the class can be accessed. )
See sample program Four (<effective C + + (2nd) > (photocopy) 59th page)[CPP]View Plain copy print?       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};   size_t Enemytarget::numtargets; In this example, the static data member Numtargets is used to count the number of objects produced.

Additionally, when designing a multithreaded operation of a class, because the thread function pthread_create () requirements under the POSIX library are global, a normal member function cannot be used directly as a thread function, you might consider using a 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.