Scope

When you declare a name, you can only use that name in specific parts of the program. Those parts where the name is valid is called the scope of the identifier.

A name is global if it is defined outside any function, class, or namespace. The scope of a global name extends from the point of declaration to the end of the file in which it is declared.

A name is local if it is declared inside of a function. The scope of a local name is from the point of declaration to the end of the block in which its declaration occurs.

A block is a section of code delimited by a pair of curly braces { }. Blocks can be nested.

The declaration of a name in a block can hide a declaration in an enclosing block or a global name. The name declared in the inner block refers to a different entity. After leaving the block, the name resumes its previous meaning. This example is from Stroustrup:

int x;       // global x; initialized to 0

void f()
{
  int x;     // first local x; not initialized
  x = 1;     // assign to first local x
  {
    int x;   // second local x; hides first local x
    x = 2;   // assign to second local x
  }
  x = 3;     // assign to first local x
}

int* p = &x; // take address of global x

Try to avoid name hiding if you can. It can easily lead to errors.

The above example illustrates a difference between global variables and local variables. If no initializer is specified for a global variable, the variable is assigned a default value (the appropriate zero value for the built-in types). Local variable definitions with no initializer results in an uninitialized variable. That is, the local variable has no well-defined value.


Burton Ma
Department of Computing and Information Science
Queen's University