Differences between C and C ++ static functions

Source: Internet
Author: User

Differences between C and C ++ static functions
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) 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 Program Design (version 2)> 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. The function is automatically released after the function call is completed, and the static type is allocated to the static storage area, 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
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, regardless of whether the class 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.
Example 1
# Include <iostream>
Using namespace STD;
Void staticlocalvar ()
{
Static int A = 0; // Initialization is performed at runtime. 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.
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", 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. 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 !!!
pay special attention to this issue in multi-threaded or recursive programming.
(for examples of non-reentrant properties, see (photoprinting) page 103-105)
The following is an example of Program 2, analyzes the security of multiple threads. (For easy description, mark the row 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. % u ", PChIP [0], PChIP [1], PChIP [2], PChIP [3]);
⑥ return strbuff;
7}< br> assume that there are two threads a and B that need to call the iptostr () function during runtime, converts a 32-bit IP address to a string in the 10-digit notation. 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.

Ii. External static variables/functions
In C, static 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.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.

3. static data member/member function (C ++ exclusive)
C ++ reused this keyword and gave 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 ( (Photocopy) page 1)
class enemytarget {
Public:
enemytarget () {++ numtargets ;}< br> enemytarget (const enemytarget &) {++ numtargets ;}< br> ~ Enemytarget () {-- numtargets ;}< br> static size_t numberoftargets () {return numtargets ;}< br> 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, 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.

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/lipps/archive/2007/05/18/1615419.aspx

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.