Question

About declarative region:

Every name is introduced in some portion of program text called a declarative region, which is the largest part of the program in which that name is valid

About scope:

In general, each particular name is valid only within some possibly discontiguous portion of program text called its scope.

What is the differences between them?

Était-ce utile?

La solution

A declarative region is a place where names can be declared in. I.e. they can be declared in a block, a class body, or in the bodies of a namespace, etc.

A scope is just some snippet of program text. If you say "the scope of this name", this phrase refers to the part of the program text that this name can be found using the names unqualified form.

Currently these two terms are in defective form in the standard, and there is a long standing active issue to fix these defects.

Autres conseils

The difference between a declarative region and a scope is like difference between a room and a location.

A declarative region (room) exists without relation to particular names. You define a class, or a function body, or a namespace - a declarative region is thereby introduced. You can then declare names into that declarative region (put things into the room); or you can leave the region devoid of any names (empty room).

Of scopes (locations) we can only talk in relation to names; there is no scope on its own, scope is always an attribute to a name (like location is an attribute of a thing). A potential scope of a name coincides with the declarative region where that name is introduced.

I'm not sure where did you take those definitions from. They do look like the same to me. However I've found this post:

In short, scope answers the question "where can I use this name?" and declaration space answers the question "where is this name unique?"

Have a look at this example:

class C {
    int x;
    void M() {
        int x;
    }
}

Scope of x is entire body of C while the declarative region is entire body of C excluding the body of M. Source:

http://blogs.msdn.com/b/ericlippert/archive/2009/08/03/what-s-the-difference-part-two-scope-vs-declaration-space-vs-lifetime.aspx

In the definitions you provided, I just see them as two sides of the same coin. The declaration area is the beginning of the lifetime of a variable, and the scope defines the end. Though colloquially, the scope typically refers to the full lifetime of the variable, from beginning to end. See below for an example.

void someFunction ()
{
    int x = 5; // declaration of x
    for (int i = 0; i < 10; ++i)
    {
        int a = 3; // declaration of a
        std::cout << a << std::endl;
    } // end of scope for a
} // end of scope for x
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top