C++ static local variables and static function examples

  • 2020-04-02 02:23:36
  • OfStack

A variable is defined in the body of the function, and stack memory is allocated to the local variable each time the program runs to the statement. However, as the program exits the function body, the system will withdraw the stack memory and local variables will be invalidated accordingly. But sometimes we need to save the value of the variable between calls. The general idea is to define a global variable to implement. However, as a result, variables no longer belong to the function itself, and are no longer only controlled by the function, bringing inconvenience to the maintenance of the program. Static local variables can solve this problem. Static local variables are stored in the global data area rather than on the stack, with each value held until the next call until the next assignment. The variable allocates memory in the global data area; Static local variables are initialized the first time the program executes to the declaration of the object, meaning that subsequent function calls are not initialized (which is important). Static local variables are generally initialized in the declaration, if not explicitly initialized, will be automatically initialized to 0 by the program; It stays in the global data area until the program runs. But its scope is local scope, when the function or statement block that defines it ends, its scope ends; Static function is mainly used to access the static members, can not directly access the non-static members of the class; Static member functions can be called without generating objects mainly for the sake of convenience. Such as


class X
{
public:
    void MethodA();
    static void MethodB();
}

So now MethodB can just call X::MethodB();
MethodA must be generated before it can be called, X X; X.M ethodA ();


//Example 3   
#include <iostream.h> 
void fn();   
void main() { 
fn(); fn(); fn(); 
} 

void fn() { 
static int n=10; //It is initialized only the first time it is called and ignored the second time
cout<<n<<endl; 
n++; 
}  


< img SRC = "border = 0 / / files.jb51.net/file_images/article/201404/20140430111012.jpg? 2014330111147 ">


Related articles: