Local variable: Difference between revisions

Content deleted Content added
Static local variables: Java does too have "static" variables
call by value subroutine parameters
Line 2:
 
Local variables are special because in most languages they are [[automatic variable]]s stored on the [[call stack]] directly. This means that when a [[Recursion (computer science)|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-effect (computer science)|side-effects]] to processes outside of the block in which they are declared.
 
Programming languages that employ ''[[call by value]]'' semantics provide a called subroutine with its own local copy of the [[function argument|arguments]] passed to it. In most languages, these local parameters are treated the same as other local variables within the subroutine. In contrast, ''[[call by reference]]'' and ''[[call by name]]'' semantics allow the parameters to act as aliases of the values passed as arguments, allowing the subroutine to modify variables outside its own scope.
 
Some advocate that all variables should be of local scope to avoid issues with [[Side-effect (computer science)|side-effects]].
Line 7 ⟶ 9:
==Static local variables==
{{main|Static variable}}
A special type of local variable, called a static local, is available in many mainstream languages, including [[C (programming language)|C]]/[[C++]], [[Visual Basic]] and [[Visual Basic .NET|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 thea special ''storage class'' keyword (e.g., <code>static</code> 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 programming|object-oriented]] languages, andalthough 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 [[Visual Basic .NET|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.