C ++ Variables

Source: Internet
Author: User

Scope: Valid range of variable names
Period of existence: the period in which the variable exists in the program.
Storage Method: auto, register, extern, static
Storage space type: Stack: variables automatically allocated and cleared, such as local variables and function parameters.
Heap: space allocated by functions such as malloc.
(In c ++, this is called a free storage zone, and the new space is called a heap)
Global/static storage area: stores global and static variables.
Constant storage: stores constants (constant strings, magic number, etc.) and cannot be modified.

 

Type

Supplement

Scope

Period

Initialization

External definition (outside function)

Global variable (external variable)

For the subsequent definition, use: Description of available extern external variables.

Global

Full Process

One Initialization

Static external variables

 

File

Full Process

External Array

 

Global

Full Process

Static Functions

 

File

N/

N/

Common functions

 

Global

N/

N/

Internal definition (in the function)

Static local Array

 

Local

Full Process

One Initialization

Static local variables

Only one value can be assigned outside the function.

Local

Full Process

One Initialization

Common local variables (automatic variables)

 

Local

Local

 

All objects (variables, arrays, and so on) that have a full life cycle have the "one-time initialization" feature, that is, they are initialized only once before the program starts (and will be skipped when an initialization statement is encountered later, of course, other value assignment statements will not be skipped ).
They are all allocated in the global/static storage area.
The right value during initialization can be an initialization expression (consisting of a text volume, a symbolic constant, or a basic operator (except for a value assignment and an auto increment or decrement operator ). if no initialization statement exists, it will be set to zero automatically (including arrays ).

**************************************** **************************************** ********

Static can be used in two ways: static in process-oriented programming and static in object-oriented programming. The former applies to common variables and functions, and does not involve classes. The latter mainly describes the role of static in classes.

Static in process-oriented design

Differences between global variables, local variables, static global variables, and static local variables

C ++ variables have different scopes based on different lifecycles at defined locations. They can be divided into six categories: global scope, local scope, statement scope, and Class scope, namespace scope and file scope.

From the scope:

Global variables have a global scope. Global variables can be defined in only one source file to act on all source files. Of course, other source files that do not contain the definition of a global variable must use the extern keyword to declare the global variable again.

Static local variables have a local scope and are initialized only once. They exist until the first initialization ends until the program is running, the difference between global variables and global variables is that global variables are visible to all functions, while static local variables are always visible only to the defined function bodies.

A local variable only has a local scope. It is an automatic object (auto). It does not always exist during the program running, but only exists during the function execution. After a function call is completed, the variable is revoked, and the occupied memory is also withdrawn.

Static global variables also have a global scope. The difference between static global variables and global variables is that if a program contains multiple files, it acts on the files that define it and cannot act on other files, the variable modified by the static keyword has the file scope. In this way, even if two different source files define static global variables with the same name, they are also different variables.

From the perspective of memory space allocation:
Global variables, static local variables, and static global variables are all allocated space in the static storage area, while local variables are allocated space in the stack.

 

 

Global variables are static storage, and static global variables are also static storage. The two are not different in storage methods. The difference between the two lies in that the scope of non-static global variables is the entire source program. When a source program is composed of multiple source files, non-static global variables are valid in each source file. The static global variable limits its scope, that is, it is valid only in the source file defining the variable, and cannot be used in other source files of the same source program. Because the scope of static global variables is limited to one source file, they can only be shared by functions in the source file. Therefore, errors in other source files can be avoided.

1) static variables will be placed in the static data storage area (data segment) (globally visible) of the program, so that the original values can be assigned during the next call. This is the difference between stack variables and heap variables.
2) The variable uses static to notify the compiler that it is only visible within the scope of the variable. This is the difference between it and global variables.

From the above analysis, we can see that after a local variable is changed to a static variable, its storage mode is changed, that is, its survival time is changed. After changing a global variable to a static variable, it changes its scope and limits its scope of use. Therefore, the description of static plays different roles in different places. Attention should be paid.

TIPS:
A. if the global variable is only accessed in a single c file, you can change the variable to a static global variable to reduce the coupling between modules;
B. If the global variable is only accessed by a single function, you can change the variable to the static local variable of the function to reduce the coupling between modules;
C. When designing and using functions that access dynamic global variables, static global variables, and static local variables, you need to consider re-import, because they are all stored in the static data storage area, which is globally visible;
D. If we need a reentrant function, we must avoid using static variables in the function (such a function is called a function with the "internal memory" function)
E. static variables must be used in a function. For example, if the return value of a function is of the pointer type, the address of the static local variable must be used as the return value. If the return value is of the auto type, the returned result is an error pointer.

Bytes -----------------------------------------------------------------------------------------------------------

Static global variable: change the scope of action without changing the storage location

Static local variable: changes the storage location and does not change the scope.

Static functions: add the static keyword before the return type of the function. The function is defined as a static function. A static function is different from a common function. It can only be seen in the file where it is declared and cannot be used by other files.

A function defined in a source file can only be called by functions in this file, but cannot be called by functions in other files of the same program. This function is also called an internal function. To define an internal function, you only need to add a "static" keyword before the function type.

Bytes ---------------------------------------------------------------------------------------------------------------

2. Object-oriented static keywords (static keywords in the class)

Static data members have the following features:

For non-static data members, each class object has its own copy. Static data members are treated as class members. No matter how many objects of this class are defined, static data members also have only one copy in the program, which is shared by all objects of this type. That is to say, static data members are shared by all objects in the class. For multiple objects in this class, static data members only allocate memory once for all objects. Therefore, the values of static data members are the same for each object, and their values can be updated;

Static data members are stored in the global data zone. Space must be allocated when defining static data members, so they cannot be defined in the class declaration. In Example 5, the statement int myclass: Sum = 0 is a member that defines static data;

Static data members follow the public, protected, and private access rules like common data members;

Because static data Members allocate memory in the global data zone and all objects in this class are shared, they do not belong to a specific class object and are visible in the scope when no class object is generated, that is, when no class instance is generated, we can operate on it;

Static data member Initialization is different from general data member initialization. The static data member initialization format is:

<Data type> <class name >:< static data member name >=< value>

Static data members of a class can be accessed in two forms:

<Class Object Name>. <static data member name> or <class type name >:< static data member name>

If the access permission of the static data member is allowed (that is, the Public Member), you can reference the static data member in the program in the above format;

Static data members are mainly used when each object has the same attribute. For example, for a deposit type, the interest of each instance is the same. Therefore, the interest should be set as the static data member of the deposit class. There are two advantages: first, no matter how many deposit-type objects are defined, interest data members share the memory allocated to the global data area, thus saving storage space. Second, once the interest needs to be changed, the interest of all deposit objects will be changed once;

Compared with global variables, static data members have two advantages:

The static data member does not enter the global namespace of the program, so there is no possibility of conflict with other global names in the program;

Information can be hidden. Static data members can be private members, but global variables cannot;

2. static member functions

Like static data members, we can also create a static member function that serves all the classes rather than specific objects of a class. Static member functions, like static data members, are internal implementation of the class and are part of the class definition. A common member function generally implies a this pointer, which points to the object itself of the class, because a common member function always belongs to a specific object of a class. Generally, this is the default value. For example, the function FN () is actually this-> FN (). However, compared with common functions, static member functions do not have the "This" pointer because they are not associated with any objects. In this sense, it cannot access non-static data members of class objects or non-static member functions. It can only call other static member functions.

Static member functions can be summarized as follows:

The keyword static cannot be specified for function definitions that appear in external classes;

Static members can access each other, including static member functions accessing static data members and accessing static member functions;

Non-static member functions can access static member functions and static data members at will;

Static member functions cannot access non-static member functions and non-static data members;

Without the additional overhead of this pointer, static member functions increase slightly compared with global functions of the class;

Call static member functions. You can use the member access operator (.) and (->) call a static member function for a class object or pointer to a class object. You can also directly use the following format:

<Class name >:: <static member function name> (<parameter table>)

Call static member functions of a class.

**************************************** **************************************** *******

Static variable declaration. It is valid within the program block, subroutine block, or function that declares it. The value is maintained and memory space is allocated throughout the program. The default value of the compiler is 0.

It is a common modifier in C ++. It is used to control the storage and visibility of variables.

2. Why is static introduced?

When a variable defined in a function is executed to its definition, the compiler allocates space for it on the stack, the space allocated by the function on the stack is released at the end of the function execution. This creates a problem: If you want to save the value of this variable in the function to the next call, how to implement it? The easiest way to think of is to define a global variable, but defining a global variable has many disadvantages, the most obvious drawback is that the access range of the variable is broken (so that the variables defined in this function are not controlled by this function ).

3. When should I use static?

A Data Object is required to serve the entire class rather than a specific object, and the encapsulation of the class is not damaged. That is, the member is required to be hidden inside the class and invisible to the outside world.

4. static internal mechanism:

Static data members must exist at the beginning of the program. Because the function is called during the running of the program, static data members cannot allocate space and initialize it in any function.

In this way, there are three possibilities for its space allocation. One is the header file of the class's external interface, where there is a class declaration; the other is the internal implementation of the class definition, there is a member function definition for the class, and the third is the global data description and definition before the main () function of the application.

Static data members must actually allocate space, so they cannot be defined in the class declaration (only data members can be declared ). The class declaration only declares the "size and specification" of a class and does not actually allocate memory. Therefore, it is wrong to write a definition in the class declaration. It cannot be an external definition of the class declaration in the header file, because it will duplicate the definition in multiple source files that use the class.

Static is introduced to inform the compiler that the variables are stored in the static storage area of the program rather than the stack space.

Data members are initialized sequentially according to the sequence in which they appear. Note that when static members are nested, ensure that the nested members have already been initialized. The order of cancellation is the reverse order of initialization.

5. Static advantages:

Memory can be saved because it is public to all objects. Therefore, for multiple objects, static data members only store one object for sharing. The value of a static data member is the same for each object, but its value can be updated. You only need to update the value of the static data member once to ensure that all objects have the same value after the update, which improves the time efficiency.

6. When referencing static data members, use the following format:

<Class name >:: <static member name>

If the access permission of the static data member is allowed (that is, the Public Member), in the program, according to the above format

To reference static data members.

7. Notes:

(1) The static member function of the class belongs to the entire class rather than the class object, so it does not have the this pointer, which leads

It only supports the static data and static member functions of the category.

(2) static member functions cannot be defined as virtual functions.

(3) Since static members are declared in the class and operated outside of the class, it is somewhat special to perform the address fetch operation on them.

The variable address is a pointer to its data type, and the function address type is a "nonmember function pointer ".

(4) because the static member function does not have the this pointer, it is almost equivalent to the nonmember function.

This creates an unexpected benefit: Being a callback function allows us to combine C ++ and C-based X W

The indow system is combined and successfully applied to the thread functions.

(5) Static does not increase the space-time overhead of the program. On the contrary, it shortens the access of the subclass to the static members of the parent class.

Time, saving sub-class memory space.

(6) Add the keyword "static" before <definition or description> to the static data member.

(7) static data members are stored statically, so they must be initialized.

(8) static member Initialization is different from general data member initialization:

Initialization is performed in the external class without static before, so as to avoid confusion with general static variables or objects;

During initialization, the access permission control characters private and public of the member are not added;

During initialization, the scope operator is used to indicate the class to which it belongs;

So we can get the format of static data member initialization:

<Data type> <class name >:< static data member name >=< value>

(9) to prevent the influence of the parent class, you can define a static variable of the same as the parent class in the subclass to avoid the influence of the parent class. Here, we need to note that static members are shared by the parent class and subclass, but we have repeatedly defined static members. Will this cause errors? No, our compiler uses a wonderful method: Name-mangling is used to generate a unique flag.

Source: feino net (http://www.diybl.com/course/3_program/c++/cppjs/20090902/173451.html)

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.