C + + Learning Note (ix): Scopes and namespaces

Source: Internet
Author: User
Tags volatile

Scope

Scope rules tell us the valid range of a variable, where it was created and where it was destroyed (that is, out of scope). The valid scope of a variable starts at its defining point, to the first closing parenthesis of the nearest opening brace pair before and after the variable is defined. That is, the scope is determined by the closest pair of parentheses where the variable resides.

(1) Global variables:

Global variables are defined outside the body of all functions, and the part of the program (and even the code in other files) can be used. The global variable is not affected by the scope (that is, the lifetime of the global variable continues until the end of the program). If you use the extern keyword in one file to declare a global variable that exists in another file, the file can use this data.

(2) Local variables:

Local variables appear within a scope, and they are confined to a function. Local variables are often referred to as automatic variables because they are automatically generated when they enter the scope and disappear automatically when they leave the scope. The keyword Auto can explicitly describe the problem, but the local variable defaults to auto, so it is not necessary to declare it as auto.

(3) Register variable

A register variable is a local variable. The keyword register tells the compiler to "access this variable as quickly as possible." Speed of access depends on reality, but, as the name implies, this is often done by placing variables in registers. This does not guarantee that it will be placed in registers or even improve access speed. This is just a hint to the compiler.

There is a limit to using the Register variable: (1) It is impossible to obtain or calculate the address of the register variable; (2) Register variables can only be declared in one block (there can be no global or static register variable). However, you can use the register variable as a formal parameter in a function (that is, in the parameter table).

In general, you should not speculate on the compiler's optimizer, because it might do better than we do. Therefore, it is best to avoid using the keyword register.

(4) Static variables

The keyword static has some unique meanings. In general, a function defines a local variable that disappears at the end of a scope in a function. When this function is called again, the storage space of the variable is recreated and its value is reinitialized. If you want to make the value of a local variable persist throughout the lifetime of the program, we can define the local variable of the function as static, and give it an initial initialization. Initialization is performed only when the function is first called, and the value of the variable between function calls remains constant, in this way the function can "remember" some pieces of information between the function calls. This is the so-called static local variable, with local scope, it is initialized only once, since the first initialization until the end of the program run has been there, and the difference between the global variable is that the global variable is visible to all functions, and static local variables are only in the definition of their own function is always visible.

We may wonder why we don't use global variables. The advantage of a static local variable is that it is not available outside the scope of the function, so it cannot be easily changed. This causes the error to be localized.

There are also static global variables, with global scope, which differs from global variables in that if a program contains multiple files, it acts on the file that defines it and does not work in other files, that is, variables modified by the static keyword have a file scope. This way, even if two different source files define static global variables of the same name, they are also different variables.

(5) External variables

extern tells the compiler that there is a variable and function, even if the compiler does not see it in the current file. This variable or function may be defined in a file or later in the current file. For example, extern int i; The compiler will know I must exist somewhere as a global variable. When the compiler sees the definition of the variable i and does not see any other declarations, I know that it has found the same declared I in front of the file.

(6) Const constant

Const tells the compiler that the name represents a constant, both internal and user-defined data types can be defined as const. If you define an object as a constant and then try to change it, the compiler will generate an error. In C + +, a const must have an initial value.

(7) volatile variables

The qualifier Const tells the compiler that "this is not going to change" (this is to allow the compiler to perform additional optimizations), while the qualifier volatile tells the compiler to "do not know when to change" to prevent the compiler from making any optimizations based on the stability of the variable.

From allocating memory space to see: Global variables, static local variables, static global variables are allocated space in the static storage, and local variables allocated space in the stack.

Name space

The purpose of using namespaces is to localize the names of identifiers to avoid naming conflicts. Without namespaces, the names of these variables, functions, and classes will all exist in the global namespace, causing many conflicts. For example, if we define a function toupper () in our own program, this overrides the ToUpper () function in the standard library, because both functions are in the global namespace. Naming conflicts can also occur in cases where a program uses two or more third-party libraries. At this point, it is quite possible that the name in one of the libraries is the same as the name in the other library, which is a conflict. This situation often occurs on the name of the class. For example, we define a stack class in our own program, and a library in our program may have a class with the same name, and the name conflicts.

Our common using namespace STD, which refers to using C + + 's own namespace, Std.

The basic form of defining the namespace is as follows:

1 namespace name 2 {3     // Code 4 }

Example:

1 namespaceCounternamespace2 {3 4     intUpperbound;5     intlowerbound;6 7     classcounter8     {9 Ten         intcount; One     Public: ACounterintN) -      { -  the             if(N <=upperbound) { -Count =N; -}Else  { -Count =Upperbound; +             } -       } +     voidResetintN) A      { at        if(N <upperbound) -             { -Count =N; -             } -         } -      intrun () { in       if(Count >lowerbound) -        { to                 returncount--; +}Else { -                 returnlowerbound; the        } *       } $     };Panax Notoginseng}

An identifier declared in a namespace is a modifier that can be directly referenced and does not require any namespace.

However, since namespaces define a scope, we need to use the scope resolution operator to refer to the objects in the namespace outside of the namespace. For example, assigning a value of 10 to a upperbound outside the scope defined by the namespace Counternamespace must be written like this:

1 ten;

Or the object that you want to declare a counter class outside the scope of the Counternamespace definition must be written like this:

1 counternamespace::counter obj;

In general, a member who wants to access the inside of a namespace outside the namespace needs to precede the member with the namespace and scope resolution operators.

The same spatial name can be declared multiple times, and this declaration is complementary, which allows the namespace to be split into several files or even different places in the same file.

For example:

1 namespaceNS2 3 {4 5 inti;6 7 }8 9  Ten  One //... A  -  - namespaceNS the  - { -  -     intJ; +  -}

Where the namespace NS is divided into two parts, but the contents of the two parts are in the same namespace. i.e. NS. The last point: namespaces can be nested. This means that you can declare additional namespaces inside a namespace.

Using keyword

If you need to refer to a member of a namespace more than once in a program, it is cumbersome to use the scope resolver to specify the namespace each time, as we have previously said. To solve this problem, the Using keyword has been introduced. Using statements are typically used in two ways:

using namespace namespace name;

Using namespace name:: member;

The namespace name in the first form is the namespace we want to access. All members in the namespace are introduced into the current scope. That is, they are all part of the current namespace and are no longer required to use the scope qualifier. The second form simply makes the specified member in the specified namespace visible in the current scope.

We use the preceding counternamespace for example, the following using statements and assignment statements are valid:

1 using // only the lowerbound is currently visible 2 Ten // This is legal because the Lowerbound member is currently visible 3 using // all members of the Counternamespace space are currently visible 4  - // This is legal because all the counternamespace members are now visible.

C + + Learning Note (ix): Scopes and namespaces

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.