variable shadowing
   HOME

TheInfoList



OR:

In
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as ana ...
, variable shadowing occurs when a variable declared within a certain
scope Scope or scopes may refer to: People with the surname * Jamie Scope (born 1986), English footballer * John T. Scopes (1900–1970), central figure in the Scopes Trial regarding the teaching of evolution Arts, media, and entertainment * Cinem ...
(decision block, method, or
inner class In object-oriented programming (OOP), an inner class or nested class is a class declared entirely within the body of another class or interface. It is distinguished from a subclass. Overview An instance of a normal or top-level class can exist on ...
) has the same name as a variable declared in an outer scope. At the level of
identifiers An identifier is a name that identifies (that is, labels the identity of) either a unique object or a unique ''class'' of objects, where the "object" or class may be an idea, physical countable object (or class thereof), or physical noncountable ...
(names, rather than variables), this is known as
name masking In programming languages, name resolution is the resolution of the tokens within program expressions to the intended program components. Overview Expressions in computer programs reference variables, data types, functions, classes, objects, libr ...
. This outer variable is said to be shadowed by the inner variable, while the inner identifier is said to ''mask'' the outer identifier. This can lead to confusion, as it may be unclear which variable subsequent uses of the shadowed variable name refer to, which depends on the name resolution rules of the language. One of the first languages to introduce variable shadowing was
ALGOL ALGOL (; short for "Algorithmic Language") is a family of imperative computer programming languages originally developed in 1958. ALGOL heavily influenced many other languages and was the standard method for algorithm description used by the ...
, which first introduced blocks to establish scopes. It was also permitted by many of the derivative programming languages including C,
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
and
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
. The C# language breaks this tradition, allowing variable shadowing between an inner and an outer class, and between a method and its containing class, but not between an if-block and its containing method, or between case statements in a
switch In electrical engineering, a switch is an electrical component that can disconnect or connect the conducting path in an electrical circuit, interrupting the electric current or diverting it from one conductor to another. The most common type of ...
block. Some languages allow variable shadowing in more cases than others. For example Kotlin allows an inner variable in a function to shadow a passed argument and a variable in an inner block to shadow another in an outer block, while
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
does not allow these. Both languages allow a passed argument to a function/Method to shadow a Class Field. Some languages disallow variable shadowing completely such as
CoffeeScript CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehensio ...
.


Example


Lua

The following
Lua Lua or LUA may refer to: Science and technology * Lua (programming language) * Latvia University of Agriculture * Last universal ancestor, in evolution Ethnicity and language * Lua people, of Laos * Lawa people, of Thailand sometimes referred t ...
code provides an example of variable shadowing, in multiple blocks. v = 1 -- a global variable do local v = v + 1 -- a new local that shadows global v print(v) -- prints 2 do local v = v * 2 -- another local that shadows outer local v print(v) -- prints 4 end print(v) -- prints 2 end print(v) -- prints 1


Python

The following
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
code provides another example of variable shadowing: x = 0 def outer(): x = 1 def inner(): x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # prints # inner: 2 # outer: 1 # global: 0 As there is no variable declaration but only variable assignment in Python, the keyword nonlocal introduced in Python 3 is used to avoid variable shadowing and assign to non-local variables: x = 0 def outer(): x = 1 def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # prints # inner: 2 # outer: 2 # global: 0 The keyword global is used to avoid variable shadowing and assign to global variables: x = 0 def outer(): x = 1 def inner(): global x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # prints # inner: 2 # outer: 1 # global: 2


Rust

fn main() //# Inner x: 1 //# Outer x: 0 //# Outer x: Rust


C++

#include int main()


Java

public class Shadow


JavaScript

ECMAScript 6 ECMAScript (; ES) is a JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262 ECMAScript is commonly used for client-side scripting o ...
introduction of let and const with block scoping allow variable shadowing. function myFunc() { let my_var = 'test'; if (true) { let my_var = 'new test'; console.log(my_var); // new test } console.log(my_var); // test } myFunc();


See also

* Overloading *
Type polymorphism In programming language theory and type theory, polymorphism is the provision of a single interface to entities of different types or the use of a single symbol to represent multiple different types.: "Polymorphic types are types whose operatio ...
*
Name binding In programming languages, name binding is the association of entities (data and/or code) with identifiers. An identifier bound to an object is said to reference that object. Machine languages have no built-in notion of identifiers, but name-objec ...


References

Variable (computer science) Articles with example Python (programming language) code