Scope (programming)

   

This article is about the use of the term in computer science. See scope for other uses.

In computer programming, the scope of an identifier refers to where and when in the program the identifier can be referenced. Scope applies to all identifiers in a program, but it is mostly used for variables, functions and classes.

For example, the scope of a variable refers to where in the program the variable can be accessed and/or modified. For a function, to where the function can be called, and so on.

Common scope levels:

  • global scope: visible from the entire program
  • file scope: visible from a single source file.
  • local scope: visible only from the local function or block where the name was declared.

Scope is usually hierarchical: a variable declared at local scope (for example, as a local variable inside a function) supersedes the same variable declared at global scope. All references to this variable inside the function will manipulate the locally-defined variable. Outside the function, they will manipulate the globally-defined variable.

Because of this automatic scope handling, careful management of variable, class and function names should be a requirement for any non-trivial program. It is considered good programming practice to make variables as narrow a scope as feasible so that different parts of your program do not accidentally interact with each other by modifying each other's variables. This also prevents Action at a distance. Common techniques for doing so are to have different sections of your program use different namespaces, or else make individual variables private through either dynamic variable scoping or lexical variable scoping.

Example

This is an example in C++.

static const int max_number_of_users = 100;
public class User {
    public static int number_of_users;
   
    public const char *name; 
    public User (const char *new_name) {
      int n = number_of_users;
      n++;
      if (max_number_of_users < n)
          abort ();
      number_of_users = n;
      name = new_name;
    }
}

In this example,

  • max_number_of_users - global variable
  • number_of_users - class variable
  • new_name - local
  • name - instance variable

See also


Retrieved from "http://www.mywiseowl.com/articles/Scope_%28programming%29"

This page has been accessed 292 times. This page was last modified 16:37, 2 Sep 2004. All text is available under the terms of the GNU Free Documentation License (see Copyrights for details).