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

Source: Internet
Author: User

Static can be used in either of the following ways:Process-orientedProgramDesignStatic andObject-Oriented ProgrammingStatic. The former applies to common variables and functions, and does not involve classes. The latter mainly describes the role of static in classes.

Differences between static global variables, local variables, static global variables, and static local variables in process-oriented design

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 perspective: 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 running of the program, but only exists during the execution of the function. 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. Static global variables limit their scopes, that is, they are 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, so as to 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 the original values can be maintained 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.


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.

Certificate ------------------------------------------------------------------------------------------------------------------------------------------------------------

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.

Certificate ------------------------------------------------------------------------------------------------------------------------------------------------------------

Differences between static global variables, local variables, static global variables, and static local variables in Object-Oriented Design

1. object-oriented static keywords (static keywords in a 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 are defined for this class, 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. Static data members follow the public, protected, and private access rules like normal data members. Because static data Members allocate memory in the global data zone and all objects in this category are shared, it is not a specific class object. Its scope is visible 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 either of the following ways: <Class Object Name>. <static data member name> or <class 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 to the static data of the deposit class as a member. 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: static data members do not enter the global namespace of the program, so there is no possibility of conflict with other global names in the program; Information Hiding can be realized. 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 object services 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 usually implies a this pointer. This Pointer Points to the object of the class, because common member functions always belong to specific objects of a class. Generally, this is the default value. For example, the function FN () is actually this-> FN (). However, compared with a common function, a static member function does not have a "This" pointer because it is not associated with any object. 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:

Function definitions that appear in external classes cannot specify the keyword static. 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 extra overhead of this pointer, static member functions increase slightly compared with global functions of the class. When calling static member functions, you can use the member access operator (.) and (->) can be used as a class object or a pointer to a class object to call a static member function. The following format can also be used directly:

<Class Name>: <static member function name> (<parameter table>) Call the static member function of the class.

========================================================== ========================================================== ====================

1. static variable declaration. It is valid within the program block, subroutine block, or function that declares it. The value is maintained and the storage 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. static data members are initialized in sequence according to the sequence in which they appear. Note that when static members are nested, make sure that the nested members have been initialized. The order of cancellation is the reverse order of initialization.

5. Static advantages: it can save memory 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. As long as the value of the static data member is updated, ensure that all objects access the same value after the update, which can improve 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), you can reference the static data member in the program in the preceding format.

7. Notes:

(1) The static member function of the class belongs to the entire class rather than the Class Object. Therefore, it does not have the this pointer, which leads to the ability to parse static data and static member functions of the class only.
(2) static member functions cannot be defined as virtual functions.
(3) because 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, 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, and the result produces an unexpected benefit: To become a callback function, this allows us to combine C ++ and C-based X w indow systems, and successfully apply them to thread functions.
(5) Static does not increase the space-time overhead of the program. On the contrary, It shortens the access time of the subclass to the static members of the parent class and saves the 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 class external body 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 the member belongs. Therefore, the static data member initialization format is obtained: <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 an error? No, our compiler uses a wonderful method: Name-mangling is used to generate a unique flag.


Download: http://dl.dbank.com/c0do9m6486

[Thank you for your reference]
Differences between static global variables, static local variables, global variables, and local variables in CC ++

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.