Scope and life cycle in C + +

Source: Internet
Author: User
Tags function prototype

Pascal's father Nicklaus Wirth once proposed a formula that shows the nature of the program: program = algorithm + data structure. Later generations gave a formula to echo: Software = program + documentation. These two formulas can be concise and clear for us to show the composition of the program and software.

The running process of the program can be understood as the processing of the data by the algorithm, the result of the running of the program, which is the result data produced by the algorithm processing data. The algorithm describes the process of data processing, corresponding to the function in the program. The data structure describes the organizational structure of a computer, corresponding to the data type in the program. The data in the program corresponds to the ubiquitous variable. For US programmers, it's all about functions, data types, and variables. Therefore, C + + refers to the scope and lifecycle of the three major programs that are part of the components: functions, data types, and variables. Here's a story.

1. The difference between scope and life cycle

The scope and the life cycle are completely two different concepts. In English, scopes are represented by "scope", and the life cycle is denoted by "duration". A scope is a static concept that is used only when compiling the source program. The scope of an identifier is the area in the source file where the identifier can legally appear independently. The life cycle is a runtime concept, which refers to the time period in which a variable exists during the entire program from loading to ending running. Since functions and data types are static concepts, they do not have a life cycle, they are always present from compile time, program run to end.

Scope levels in C + + include file domains (global scope), namespace domains, class domains, function scopes, and code block scopes (local domains).

2. Scope of functions

Functions are divided into class member functions and global functions.

member functions of the class:
-Scope: Class domain.
-Life cycle: None (program run time is always present).
-Reference method: Other files to use must be referenced with the dot operator (.) or scope operator (::).
-Memory Distribution: code area.
-Note: Class member functions can be defined in the class, that is, defined in the header file, when the class is contained by a different source file is not reported as a redefinition error, because the scope is limited to the class body.

Examples are as follows:

//main.cppclass test{private:    int i;public:    voidshow()    {        cout<<"i:"<<i<<endl;    }};int main(int argc,char* argv[]){    test t;    t.show()}

Global functions:
-Scope: File domain (global scope).
-Life cycle: None (program run time is always present).
-Reference method: The function prototype must be declared before use in other files.
-Memory Distribution: code area.
-Note: If a global function with the same name is defined in two source files, a redefinition error will occur when connecting.

Examples are as follows:

//function.cppvoid printHello(){    cout<<"hello world"<<endl;}//main.cppvoid printHello();int main(int argc,char* argv[]){    printHello();}
3. Scope of data types

The data class types in C + + are divided into basic data types and non-basic data types, and non-basic data types are divided into composite data types and constructed data types. For data types in C + +, see my other blog:c++ data type.

basic Data type:
Basic data types include integer (int), real (float and double), character (char), Boolean (bool), and no-value (void).

    • Scope: File domain (global scope).
    • Life cycle: None (program run time always exists).
    • Reference method: No declaration, direct use.
    • Memory Distribution: Code area.

composite data type:
Composite data types include: Arrays (type[]), pointers (type*), references (type&), enumerations (enums).

If the composite data type is a composite that constructs a data type, its scope is consistent with the construction data type. The enum enum type has the same scope as the constructed type.

To construct a data type:
-Scope: The domain where the type definition resides, and other files are not visible.
-Life cycle: None (program run time is always present).
-Reference method: The other file is defined first and then used by the scope operator.
-Memory Distribution: code area.
-Note: If a construct with the same name is defined in two source files as long as the file does not contain each other, no redefinition error occurs because the data type does not have external connectivity.

Examples are as follows:

//main.cppnamespace dd{   class test   {   private:    int i;   public:    void show()    {        cout<<"i:"<<i<<endl;    }   };}usingnamespace dd;//引用命名空间域中的构造类型test,否则无法使用int main(int argc,char* argv[]){    test t;    t.show();}
4. Scope and life cycle of variables

The variables we face are mainly divided into global variables, global static variables, local variables and local static variables. The following one by one describe their scope and life cycle.

Global Variables:
-Scope: Global scope (global variables can be used for all source files only if they are defined in one source file);
-Life cycle: The program has been running for a long time;
-Reference method: The global variable to be referenced must be declared with the extern keyword in other files. ;
-Memory Distribution: global/static storage area;
-Note: If a global variable of the same name is defined in two files, the connection error: variable redefinition.

Examples are as follows:

//define.cpp  int1;  //main.cpp  externint g_iValue;  int main()  {      cout << g_iValue;      return0;  }  

Global static variables:
-Scope: File scope (visible only in defined files);
-Life cycle: The program has been running for a long time;
-Memory Distribution: global/static storage area;
-Definition method: Static keyword, const keyword;
-Note: As long as the files do not contain each other, in two different files can be defined exactly the same two static variables, they are two completely different variables.

Examples are as follows:

//define.cpp  constint iValue=8;   //main.cppint iValue;  staticconstint iValue_2;  staticint iValue_3;  int main(int argc,char* argv[]){    cout<<"iValue:"<<iValue<<endl;    return0;}

Local Variables:
-Scope: Local scope (visible only in local scope, such as function field, code block field);
-Life cycle: The program runs out of local scope is destroyed;
-Memory distribution: stack area;
-NOTE: The auto indicator is marked.

Examples are as follows:

void print(){    int a=0;    cout<<a<<endl;}

local static variables:
-Scope: Local scope (visible only in local scope);
-Life cycle: The program has been running for a long time;
-Memory Distribution: global static storage area;
-Definition method: Local scope is defined with static;
-Note: It is only initialized once, and lock protection is required in multiple threads.

Examples are as follows:

voidfunction()  {      static0;  }  
5. Expand the Knowledge point

1. Variable Storage descriptor
There are four storage classes in the C language that provide storage descriptor auto,register,extern,static descriptions. The four storage class specifiers have two storage periods: automatic storage period and static storage period. where auto and register correspond to the automatic storage period. A variable with an automatic storage period enters the block that declares the variable, it exists when the block is active, and is revoked when the block is exited. The static storage period is always present from the time the program loads and runs to the end of the program.

2. Static usage Recommendations
(1) If the global variable is accessed only in a single C file, the variable can be modified to a static global variable to reduce the coupling between modules;
(2) If the global variable is accessed only by a single function, the variable can be changed to the static local variable of the function to reduce the coupling degree between the modules;
(3) When designing and using functions that access dynamic global variables, static global variables, static local variables, you need to consider the reentrant problem, because they are placed in a static data store and can be shared by other functions;
(4) If we need a reentrant function, then we must avoid functions that use static variables such as functions called "internal memory" functions;
(5) The function must use the static variable condition: For example, when the return value of a function is a pointer type, it must be the address of the static local variable as the return value, and if the auto type, it is returned as a wild pointer.

Reference documents

[1] http://blog.csdn.net/yunyun1886358/article/details/5632087
[2] Advanced Step-by-step tutorial for C + + Chen Gang. Wuhan University Press

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Scope and life cycle in C + +

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.