Static keyword for C + +

Source: Internet
Author: User

There are two uses for the static of C + +: Static in process programming and static in object oriented programming. The former is applied to ordinary variables and functions and does not involve classes; the latter mainly describes the role of static in class.

Static in process-oriented design

1. Static Global variables

The variable is defined as a static global variable before the global variable, plus the keyword static. Let's first give an example of a static global variable, as follows:

//Example 1
#include <iostream.h>
void fn();
static int n; //定义静态全局变量
void main()
{
   n=20;
   cout<<n<<endl;
   fn();
}
void fn()
{
   n++;
   cout<<n<<endl;
}

Static global variables have the following characteristics:

The variable allocates memory in the global data area;

Uninitialized static global variables are automatically initialized by the program to 0 (the value of the automatic variable is random unless it is explicitly initialized);

A static global variable is visible to the entire file in which it is declared, but not to the file; Static variables allocate memory in the global data area, including the static local variables to be mentioned later. For a complete program, the distribution in memory is shown below:

Code Area
Global Data area
Heap Area
Stack area

The dynamic data generated by new in general program is stored in the heap area, and the automatic variables inside the function are stored in the stack area. Automatic variables typically release space as the function exits, and static data (even static local variables within the function) is stored in the global data area. The data in the global data area does not free up space because of the exit of the function. Attentive readers may find that the code in Example 1 will

static int n; //定义静态全局变量

To

int n; //定义全局变量

The program still works.

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.