CMP EMBEDDED.COM

Login | Register     Welcome Guest  
HOME DESIGN PRODUCTS COLUMNS E-LEARNING CONFERENCES CODE FORUMS/BLOGS NEWSLETTERS CONTACT FEATURES RSS RSS

Scope regions in C and C++



Embedded Systems Design

Most programmers, not just C and C++ programmers, refer to names declared in an inner scope (a block scope) as local names, and to names declared at the outermost scope (file scope) as global names. The C++ standard uses the terms local and global in this sense, but the C standard rarely does.

The exact point that a name's scope begins depends on the way that name is declared.

The scope of such a name begins just after the end of its declarator and before its initializer, if present. A declarator is the part of an object or function declaration consisting of a name being declared, possibly surrounded by operators such as *, [], and (). For example:


long int *p = NULL, x[N];

has two declarators, *p and x[N]. In this example, p's scope begins at the = (equal sign), and x's scope begins at the semicolon.

The scope of a structure, union, or enumeration tag begins just after the appearance of the tag in the type specifier that first declares the tag. For example, the name s appearing in:


struct s
    {
    ...
    };

is a tag. The names of unions and enumerations are also tags. The scope of s in the above declaration begins at the opening brace immediately after s.

Similarly, the general form of an enumeration definition is:


enum tag { enumerator, enumerator, ...,     enumerator };

Each enumerator is an identifier that names a constant, optionally followed by an = and an expression that specifies the constant's value. The scope of an enumeration constant begins just after the appearance of its defining enumerator.

Consider:


enum color { red, green = 2, blue = 4 };

Here, red's scope begins at the first comma, green's begins at the second, and blue's begins at the closing brace.

According to the C standard, a name in an inner scope can hide a name from an outer scope. For example, in Listing 1, the object k local to function g hides the global object k. The local k hides the global one in the sense that, when the compiler looks up k in the scope of the local k, it finds only the local k, never the global one. Thus, the assignment in g modifies the local k, not the global one.

The C++ standard explains the behavior of nested scopes differently, but the effect is pretty much the same.

1 | 2 | 3 | 4

Rate this article: Low High
Current rating
  • .
Embedded.com Career Center
Looking for a new job?
SEARCH JOBS

Browse all jobs

SPONSOR
RECENT JOB POSTINGS





 :