C | Differences between static global variables, static local variables, global variables, and local variables in C ++

Source: Internet
Author: User

There are two ways to use static: process-orientedProgramStatic in design and static in object-oriented programming. The former applies to common variables and
Function, which does not involve classes. The latter mainly describes the role of static in classes.

 
I. 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 of the defined positions. They can be divided into six types: Global scopes and local scopes.
Scope, statement scope, 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
The source file that does not contain the global variable definition must be declared again with the extern keyword.
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 only define their own function bodies.
Visible.
A local variable only has a local scope. It is an automatic object. It does not exist until the program is running, but only runs
A function exists during a row. After a function call is executed, 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 defining them.
In other files, that is, variables modified by the static keyword have a file scope. In this way, even if two different
The source files all 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, the non-static
Global variables are valid in each source file. The static global variable limits its scope, that is, only the source file that defines the variable
It is effective in the file, 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,
Only functions in the source file can be used for public use, because this can avoid errors in other source files.
1) static variables will be placed in the static data storage area (data segment) (globally visible) of the program, so that
To keep the original value assigned. 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. Set global
After a variable is changed to a static variable, it changes its scope and limits its scope of use. So the description of static is different.
The role is different. 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
All are 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:
Functions with "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. Static functions are different from common functions,
It can only be seen in the file that declares it and cannot be used by other files.
A function defined in a source file can only be called by functions in this file, but not by other files in the same program.
Function call, which is also called an internal function. To define an internal function, you only need to add a "static" keyword before the function type, that is
Yes.
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. Regardless of
As 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
Object sharing. 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 static data member defined;
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, it is not a specific class object.
When no class object is generated, its scope is visible, 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 in the above format in the program
Personnel;
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
Same. Therefore, the interest should be set to the static data of the deposit class as a member. There are two advantages: first, no matter how many deposit classes are defined
Objects and interest data members share the memory allocated to the global data zone, saving storage space. Second, once the interest needs to change,
The interest of all deposit objects changes 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 the specific
Image Service. Static member functions, like static data members, are internal implementation of the class and are part of the class definition. Ordinary Member letter
Generally, the number implies a this pointer, which points to the object of the class, because common member functions always belong to a specific class.
Specific object. Generally, this is the default value. For example, the function FN () is actually this-> FN (). However, compared with common functions
Because the member function is not associated with any object, it does not have this pointer. In this sense, it cannot access a class object.
And cannot access 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 operators (.) and (->) to call static member functions for a class object or a 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 stored during the entire program.
Storage space. 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. As you know, the function is on the stack.
The allocated space will be released at the end of the function execution, resulting in a problem: If you want to save the value of this variable in the function
How to implement one call? 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 within the class.
Is invisible to external users.
4. static internal mechanism:
Static data members must exist at the beginning of the program. Because the function is called during the program running, the static data member cannot
Allocate space and initialize 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 class defined
Internal implementation, where the class member function definition is available; third, 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 ). Class declaration only declares one class
Does not allocate the actual memory. Therefore, it is wrong to write the definition in the class declaration. It cannot contain classes in header files.
Declared external definition, because it will cause repeated definition in multiple source files using this 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 all
Shared object. The value of a static data member is the same for each object, but its value can be updated. As long as the value of the static data member is greater
The new time ensures that all objects access the same value after 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. There is a need
Note: static members are shared by the parent class and subclass, but we have repeatedly defined static members. Will this cause an error? No,
Our compiler adopts a wonderful method: Name-mangling Used to generate a unique flag.

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.