Variable shadowing

In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. At the level of identifiers (names, rather than variables), this is known as name masking. 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, which first introduced blocks to establish scopes. It was also permitted by many of the derivative programming languages including C, C++ and Java.

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 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 does not allow these. Both languages allow a passed argument to a function/Method to shadow a Class Field.[1]

Some languages disallow variable shadowing completely such as CoffeeScript[2] and V (Vlang).[3]

  1. ^ "From Java to Kotlin and Back Again". Archived from the original on 2020-11-28. Retrieved 2021-10-04.
  2. ^ "Please introduce explicit shadowing · Issue #2697 · jashkenas/Coffeescript". GitHub. Archived from the original on 2021-10-04. Retrieved 2021-10-04.
  3. ^ "Vlang documentation- "Unlike most languages, variable shadowing is not allowed"". GitHub. Retrieved 2024-06-27.