Introduction to C++ scope, variable scope, life cycle and variable classification

Introduction to C++ scope, variable scope, life cycle and variable classification

Scope in C++ refers to the visible and accessible scope of a variable, function, or other identifier.

Variable scope (Variable Scope) refers to the life cycle and visibility of variables, that is, which parts of the variable can be used in the program. According to scope (Scope) variables can be classified into global variables and local variables.

It can also be classified according to the life cycle (Lifetime). Variables can be classified into static variables (Static Variables) and member variables (Member Variables).

C++ scope (scope )

Scope in C++ refers to the scope of visibility and validity of variables, functions, and other identifiers. Scope specifies where in a program an identifier can be accessed or referenced. See Scope - cppreference.com

There are the following scopes in C++: Block Scope, Function Parameter Scope, Namespace Scope, Class Scope, and Enumeration Constant Scope ( Enum Constant Scope), Template parameter scope.

  1. Block Scope: Variables declared inside a code block have block scope and are only visible within the code block, including loops, conditional statements, etc.
  2. Function Parameter Scope (Function Parameter Scope): Function parameters also have their own scope, which is only valid inside the function, allowing local variables with the same name to hide function parameters.
  3. Namespace Scope: Identifiers defined in a namespace have namespace scope and can be accessed throughout the namespace.
  4. Class Scope: Class members (including variables, functions, etc.) have class scope and can be accessed inside the class and accessed through objects or pointers.
  5. Enum Constant Scope: Constants in an enum type have constant scope and can only be accessed within the enum type.
  6. Template parameter scope (Template Parameter Scope): Template parameters in template classes or functions have their own scope and are only valid within the template definition.

In C++, scope (Scope) and variable scope (Variable Scope) are not exactly the same, although they are closely related.

Scope (Scope) refers to the visible and effective scope of identifiers (such as variables, functions, etc.) in the program. Scope specifies where an identifier can be accessed or referenced. Scope covers the entire program, from the global scope to smaller scopes (such as inside code blocks, inside functions, etc.).

The scope of a variable (Variable Scope) refers to the visible and valid scope of a variable declared somewhere in the program. The scope of a variable is an application of scope, which determines where the variable can be used and the life cycle of the variable.

Therefore, scope is a broader concept that can include various identifiers (such as functions, classes, namespaces, etc.), while the scope of variables specifically refers to the scope of visibility and validity of variables in the program.

The scope of variables in C++ (Variable Scope )

In C++, the scope of a variable can be determined by where it is declared. In different scopes, the visibility and effective scope of variables will be different. The following are several common variable scopes.

★Global scope (Global scope): Global scope means that variables are visible throughout the program. Variables declared outside any function or code block have global scope. These variables are created when the program starts executing and destroyed when the program ends. For example:

#include <iostream>
int x = 10; // 全局变量

int main() {
    std::cout << x << std::endl; // 输出:10
    return 0;
}

In the above example, the variable x is accessed in the main function because it has global scope.

★Function scope (Function scope): Function scope means that the variable is only visible within the function. Variables are declared inside a function and can only be accessed within the same function. Variables at function scope are created when the function executes and destroyed when the function ends. For example:

#include <iostream>

void printNumber() {
    int num = 5; // 函数作用域中的变量
    std::cout << num << std::endl; // 输出:5
}

int main() {
    printNumber();
    // std::cout << num << std::endl; // 错误:变量num不在作用域内
    return 0;
}

In the above example, the variable num is only visible inside the printNumber function.

★Code block scope (Block scope): The code block scope means that the variable is only visible inside the code block. Variables are declared inside any code block (such as if statement, loop, etc.) and can only be accessed within the same code block or other code blocks nested within this code block. Block scopes can be nested, and inner code blocks can access variables declared in outer code blocks, but not vice versa. For example:

#include <iostream>

int main() {
    if (true) { // 代码块作用域
        int num = 5; // 代码块作用域中的变量
        std::cout << num << std::endl; // 输出:5
        {
            std::cout << num << std::endl; // 输出:5,嵌套代码块中仍然可见
        }
    }
    // std::cout << num << std::endl; // 错误:变量num不在作用域内
    return 0;
}

In the above example, the variable num is only visible in the block of code where the if statement is located.

★Function parameter scope (Function parameter scope): Function parameters also have their own scope, and they are valid inside the function. Function parameter scope means that these parameters are visible within the entire function. For example:

#include <iostream>

void printNumber(int num) { // 函数参数作用域中的变量
    std::cout << num << std::endl; // 输出由传入的参数值决定
}

int main() {
    printNumber(10); // 输出:10
    return 0;
}

In the above example, the function parameter num is visible inside the entire printNumber function.

Note that the scope of variables is determined by the declaration position, so the same variable name can be used in different scopes. As such, they represent different variables. When a variable with the same name as in the outer scope is declared in the inner scope, the variable in the inner scope hides the variable with the same name in the outer scope. For example:

#include <iostream>

int x = 5; // 全局变量

void printNumber() {
    int x = 10; // 局部变量,隐藏了全局变量x
    std::cout << x << std::endl; // 输出:10
}

int main() {
    std::cout << x << std::endl; // 输出:5,全局变量x
    printNumber();
    return 0;
}

In the above example, the local variable x declared inside the function printNumber hides the global variable x, so the value of x output inside the function is 10, while the value of x output in the main function is 5.

★Class scope (Class Scope): Variables declared inside the class have class scope and can be accessed by all member functions in the class. Variables at class scope are created when the object is created and destroyed when the object is destroyed. For example:

#include <iostream>

class MyClass {
public:
    int x; // 类作用域中的变量

    void printX() {
        std::cout << "类作用域中的变量:" << x << std::endl;
    }
};

int main() {
    MyClass obj;
    obj.x = 10; // 修改类作用域中的变量
    obj.printX(); // 输出类作用域中的变量

    return 0;
}

run output

Variables at class scope: 10

Lifetime _

Lifetime refers to the time period during which a variable or object exists. It starts when a variable or object is created and ends when it is destroyed.

For variables, the life cycle includes the stages of variable creation, initialization, use, and destruction. During the creation phase of a variable, memory space is allocated to the variable and initialized according to the defined type. In the use phase of variables, operations such as reading and modifying variables can be performed. Finally, when the scope of the variable ends or the memory is explicitly released, the variable is destroyed and the memory space it occupies is freed.

For objects, the life cycle is similar. The life cycle of an object includes the stages of object construction, use, and destruction. During the construction phase of an object, the constructor is called to initialize the member variables of the object. In the use stage of the object, you can call its member functions to perform various operations through the object. Finally, when the object is no longer used or goes out of scope, the destructor is called to clean up the resources occupied by the object.

C++ provides flexible ways to manage the life cycle of objects and variables, such as manually creating and destroying objects.

Variables allocated by the programmer using the new operator are known as dynamically allocated variables. In C++, the new operator is used to dynamically allocate memory space on the heap and return a pointer to the memory space.

Unlike statically allocated variables, such as local variables allocated on the stack, the lifetime of a dynamically allocated variable is not limited by its scope. They persist until explicitly freed or deleted.

Variables allocated via the new operator need to free memory manually to avoid memory leaks. Use the delete operator to free a dynamically allocated variable in order to return the memory to the system.

The following is an example of dynamic memory allocation and deallocation using new and delete:

int* dynamicVariable = new int; // dynamically allocate an integer variable

// operate with dynamicVariable

delete dynamicVariable; // release memory

Please note that dynamically allocated variables require us to manually manage their life cycle to ensure that the memory is released in time when it is no longer needed to avoid memory leaks and resource waste.

variable classification

According to the scope (Scope) and life cycle (Lifetime), variables can be classified.

Global variables and local variables are divided according to scope. The scope of global variables (Global Variables) is the entire program, and the scope of local variables (Local Variables) is in the function or statement block to which they belong.

Static variables and member variables are divided according to the life cycle. The declaration cycle of static variables (Static Variables) is the entire running period of the program, and the life cycle of member variables (Member Variables) is associated with the life cycle of the object to which it belongs. A static variable is declared inside a function or inside a class, and keeps its value persistent across multiple function calls. Member variables are variables declared inside the class, and each class object has an independent copy.

Global Variables (Global Variables ), Local Variables (Local Variables )

According to scope (Scope) variables can be classified into global variables and local variables.

Global variables are variables declared outside any function, they have global scope and can be accessed throughout the program. Global variables are created when the program starts executing and destroyed when the program ends.

Local variables (Local Variables) are variables declared inside a function. They have function scope or block scope and can only be accessed within the function or code block to which they belong. Local variables are created when the function or code block to which they belong is executed, and are destroyed after the function call ends or the code block executes.

Differences between global variables and local variables:

Scope is different: global variables are visible throughout the program, while local variables are only visible within the function or code block they belong to.

The storage location is different: global variables are stored in the static storage area, and local variables are usually stored on the stack.

The life cycle is different: global variables exist during the execution of the program, while local variables exist during the execution of the function or code block to which they belong.

It is important to note that global variables should be used with caution, as they have persistent effects on the entire program state and can lead to naming conflicts. To avoid these problems, try to limit the scope of variables to their necessary scope and use global variables only when needed.

The relationship between global variable, local variable and variable scope in C++

In C++, there is a certain relationship between global variables, local variables, and the scope of variables. The following is the relationship between them:

Global variables: Global variables (Global Variables) are variables declared outside any function, have global scope and can be accessed throughout the program. They are created when the program starts executing and destroyed when the program ends. Global variables can be used by any function in the program, including the main function (main) and other custom functions. Global variables are visible and accessible to all functions in the program.

Local variables: Local variables (Local Variables) are variables declared inside a function, have function scope or block scope, and can only be accessed within the function or code block to which they belong. Local variables are created when the function or code block to which they belong is executed, and are destroyed after the function call ends or the code block executes. The scope of local variables is limited to the function or code block in which they are declared, and cannot be accessed outside of this scope.

Precautions:

Within the same scope, variable names must be unique, otherwise naming conflicts will occur.

When a global variable and a local variable have the same name, the local variable will be used first when accessing the name inside a function.

There can be variables with the same name in nested scopes. Variables in inner scopes override variables in outer scopes. In the inner scope, a variable with the same name will refer to the variable in the inner scope. When leaving the inner scope, the variables in the outer scope will be visible again.

Inside a function, global variables can be accessed through the scope resolution operator (::) to distinguish local variables with the same name.

The following example shows the use of global and local variables in C++:

#include <iostream>

// 全局变量
int globalVariable = 10;

void func() {
    // 局部变量
    int localVariable = 5;
    
    // 打印全局变量和局部变量
    std::cout << "全局变量 globalVariable 的值: " << globalVariable << std::endl;
    std::cout << "局部变量 localVariable 的值: " << localVariable << std::endl;
}

int main() {
    func();
    
    // 这里无法访问局部变量 localVariable
    std::cout << "全局变量 globalVariable 的值: " << globalVariable << std::endl;
    
    return 0;
}

Example output:

Value of global variable globalVariable: 10
Value of local variable localVariable: 5
Value of global variable globalVariable: 10

Static Variables and Member Variables

According to the life cycle (Lifetime) to classify variables can be classified into static variables (Static Variables) and member variables (Member Variables).

Static variables (Static Variables) are variables declared inside a function or inside a class, and have static storage persistence. This means they retain their value across each function call or class instantiation, and are not reinitialized between calls.

In C++, static variables are declared using the static keyword. The difference between static variables and ordinary variables lies in their life cycle and scope. Ordinary variables are destroyed after the function is executed, while static variables exist throughout the program and will only be destroyed once. The scope of static variables is also different, a static variable is globally visible in the file where it is declared, but not in other files. The scope of a normal variable is limited to the scope in which it is declared.

For example:

#include<iostream> 
using namespace std;
void func() {
    static int count = 0;
    count++;
    cout << "Count: " << count << endl;
}

int main() {
    func(); // 输出:Count: 1
    func(); // 输出:Count: 2
    func(); // 输出:Count: 3
    return 0;
}

In the above example, the variable count is declared as a static variable, which maintains its value every time the func function is called, realizing the function of counting.

Member variables (Member Variables) are variables defined in a class, used to describe the properties and status of the class. Member variables can be accessed and used throughout the class. Typically, each object has its own set of member variables whose values ​​are independent of each other.

In C++, the definition of member variables is usually placed in the class declaration, and there is no specific assignment. When an object of a class is created, each member variable will be assigned a default value, for example, a member variable of integer type will be assigned a value of 0, and a member variable of character type will be assigned a null character.

For example:

In the example, the Rectangle class has two member variables width and height. We create an object called rect and use the dot operator (.) to set the value of the member variable. Then access the value of the member variable through the dot operator and calculate the area of ​​the rectangle.

Note that access to member variables can be controlled based on access specifiers in the class. For example, if you define member variables as private, you can only access and modify the values ​​of these variables inside the class.

Static variables declared inside a class are class static member variables .

Static member variables declared inside a class have a separate copy between each class object, which is shared among all objects of that class. For example:

#include<iostream> 
using namespace std;

class MyClass {
public:
    static int count; // 类静态成员变量声明
    
    MyClass() {
        count++;
    }
};

int MyClass::count = 0; // 在类外部初始化静态成员变量

int main() {
    MyClass obj1;
    cout << "Count: " << obj1.count << endl; // 输出:Count: 1
    
    MyClass obj2;
    cout << "Count: " << obj2.count << endl; // 输出:Count: 2
    
    return 0;
}

In the above example, the static member variable count is declared as part of the class MyClass, so it is independent of each object instance of the class. The value of count is incremented each time a new MyClass object is created. Static member variables are accessed through the class name and scope resolution operator ::.

In C++, in addition to the common variable types introduced above, there are:

Parameter Variables: The parameters of a function are also variables, which are used inside the function. The scope of the parameter variable is limited to the inside of the function. After leaving the function, the storage space allocated by it will be released automatically—the formal parameter will be released after the function exits was destroyed afterwards.

External variable (extern variable): An external variable refers to a variable declared in one file, defined and used in other files. In C++, external variables are declared using the extern keyword.

etc.

Summary :

Scope in C++ refers to the visible and accessible range of a variable, function, or other identifier.

Variable scope refers to the life cycle and visibility of variables, that is, which parts of the variable can be used in the program.

Global variables and local variables are classified according to scope. The scope of global variables is the entire program, and the scope of local variables is in the function or statement block to which they belong.

Static variables and member variables are classified according to the life cycle (Lifetime). The life cycle of a static variable is the entire program running period, and the life cycle of a member variable is associated with the object to which it belongs.

Guess you like

Origin blog.csdn.net/cnds123/article/details/132234436