Local variable

From Wikipedia, the free encyclopedia

In computer science, a local variable is a variable that is given local scope. Such variables are accessible only from the function or block in which it is declared.

Local variables are special because in most languages they are stored on the call stack directly. This means that when a recursive function calls itself, local variables in each instance of the function are given separate memory address space. Hence variables of this scope can be declared, written to, and read, without any risk of side-effects.

Some advocate that all variables should be of local scope to avoid issues with side-effects. In other cases, programming paradigms and languages themselves, such as the functional programming paradigm and the Haskell language require all "variables" (or the closest equivalent under that paradigm to variables) to be of local scope, and the functionality of the program is achieved only by passing local variables from one function to another.

[edit] Static local variables

Main article: Static variable

A special type of local variable, called a static local, is available in many mainstream languages, including C/C++, Visual Basic and VB.NET, which allows a value to be retained from one call of the function to another. In this case, recursive calls to the function also have access to the variable. In all of the above languages, variables are declared as such with the static keyword.

Static locals in global functions can be thought of as global variables, because their value remains in memory for the life of the program. The only difference is that they are only accessible through one function. Static locals can also be declared in class-level functions in the above object-oriented languages, and the behaviour differs depending on the language:

  • In C++, static locals declared in class-level functions are shared across all objects. That is, they act like static class-level variables.
  • In Visual Basic and VB.NET, static locals declared in class-level functions are local to the object. That is, they act like non-static class-level variables, and each object has its own copy of the variable.

Stricter and more formal object-oriented languages such as Java and C#, do not allow local variables to be declared static at all.

Note: This is distinct from other usages of the static keyword, which has several different meanings in various other languages.

In other languages