C vs C + + static function difference

Source: Internet
Author: User
Tags sprintf string format
C vs C + + static function difference
C with C + + static the difference between functions
The static keyword is C, C + + in the existence of keywords, it is mainly three ways to use, the first two are only refers to the use of the C language, the third in C + + use (c,c++ specific subtle operation is not the same, this article in 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 kinds of auto, static, register (<c Language Program Design (second Edition) > Tan Haoqiang, 第174-175 page) according to storage form
Static local variables are three points different than auto type (normal) local variables
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 are initialized at the first run of the module 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)
Characteristics: "Memory" of static local variables and "global" of life period
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
#include <iostream>
using namespace Std;
void Staticlocalvar ()
{
static int a = 0; Initialize once during runtime, no initialization when next call
cout<< "A=" <<a<<endl;
++a;
}
int main ()
{
Staticlocalvar (); First Call, Output a=0
Staticlocalvar (); Second call, memory of the first exit value, Output a=1
return 0;
}
Application:
Use "Memory" to record the number of function calls (sample program one)
Using the "global" of the lifetime, the problem of "return a pointer/reference to a" is improved. 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:
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;
}

Precautions:
1. "Memory", the program is very important to run the repeatability, and the static variable "memory" to destroy this repeatability, resulting in different times to run the results may be different.
2. Global and uniqueness of the "lifetime". The storage space of the ordinary local variables is allocated on the stack, so each time the function is called, the allocated space may be different, and the static has the characteristics of global uniqueness, each call points to the same memory, which causes a very important problem----Non -reentrant !!!
In this way, we should pay special attention to this problem in multithreaded programming or recursive programming.
(Non-reentrant examples can refer to <effective C + + (2nd) > (photocopy) 第103-105 page)
For example program two, the following is an analysis of the security in multi-threaded situations. (for the convenience of description, mark the uplink number)
①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;
⑦}
Suppose there are now two threads that need to invoke the IPTOSTR () function during the a,b run to convert a 32-bit IP address into a string of 10-in-point. Now A first obtains the execution opportunity, executes IPTOSTR (), the incoming parameter is 0x0b090a0a, the sequence execution should return the pointer store content is: "10.10.9.11", now executes to the ⑥, loses the execution right, dispatches to the b thread execution, b thread passes in The parameter is 0xa8a8a8c0, executed to ⑦, and the contents of the static storage area are 192.168.168.168. When the dispatch to A is performed, the execution continues from the ⑥,as Strbuff the global uniqueness of , content has been B Thread flush out, the 192.168.168.168 string is returned and is no longer a 10.10.9.11 string.

Second, external static variables/functions
Static in C has a second meaning: a global variable and function that represents an inability to 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 the way of storage, but the scope of the function is limited to this file (so called internal function). 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 advantage of using internal functions is that different people write different functions without worrying about the functions they define, or whether they have the same name as functions in other files.
Sample program Three:

File1.cpp

static int VarA;
int Varb;
extern void Funa ()
{
......
}

static void Funb ()
{
......
}

File2.cpp

extern int Varb; Using global variables defined in File1.cpp
extern int VarA; Error! VarA is a static type and cannot be used in other files
extern VOD Funa (); Using the functions defined in File1.cpp
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 is different from the previous one: a variable and function that represents a class other than any particular object belonging to the 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 when a normal member function is called, the this pointer needs to be passed in, and when the static member function is called, there is no this pointer.)
See sample program Four (<effective C + + (2nd) > (photocopy) 59th page)
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 objects produced.
Other than thatWhen you design a multithreaded operation of a class , as POSIX the thread functions under the library pthread_create () The requirements are global , Normal member functions cannot be directly as thread functions , may consider using Static member functions do thread functions .
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.