Scope

scope -
The scope of an identifier is the region of a source program within which it represents a certain thing.

Another definition:

Scope -
Scope is the context that gives meaning to a name.

Scope applies to identifiers including variable names, functions names, class names.

Variable Properties

Each variable has:

Scope and storage duration are separate issues.

Scopes in C++ - Block and Global

1. Block scope
  • An identifier declared within a block has block scope. Blocks are delimited by ``{'' and ``}''. Also
    • The formal parameters of a function have block scope within the body of the function even though they are not actually defined within the body.
    • Variables defined in a for loop header have a scope limited to the body of the for loop.
  • A block scope identifier may be referenced from the point of declaration until the end of the block in which it is declared. This includes blocks nested within, unless the identifier is shadowed (see below).
  • Variables with block scope are called local variables.
  • Block scope variables have automatic storage duration by default.
2. File, program scope,
C++ global namespace
  • An identifier declared outside a function is ``known'' in all functions from the point of declaration until the end of the file unless the identifier is shadowed (see below).
  • Variables with this scope are called global variables.
  • In C++ these variables are in the global namespace.
  • Global variables have static storage duration by default.
  • Avoid using global variables.

Scopes in C++ - Declaration, Namespace, Class

3. Function declaration scope
  • The optional variable names used in function declarations (function prototypes) have meaning only in the function declaration.
4. Namespaces
  • Namespaces provide additional large scale scoping capabilities. For example, the standard library functions are in namespace std. The using namespace std line brings everything in the std namespace into the global namespace.
5. Class scope
  • Classes (and structs) are used to define new types. A class body defines a scope. The declarations of the class members within the class body introduces the member names into the scope of their class. (More on classes later.)

Shadowing

shadowing -
Shadowing is when a block scope variable with the same name as a file scope variable or an ``outer'' block scope hides or shadows those variables and will be the one to be referenced.

Shadowing example:

void func()
{
   int abc = 5;
   {
       int abc = 9;    // The scope of this abc is the block around it
       cout << abc;    // 9 is output
   }
}

slides