Variable shadowing
Variable shadowing happens when a variable declared inside a scope has the same name as one outside that scope. The inner variable hides the outer one in that region, so which variable you refer to depends on the language’s rules for resolving names.
Origins and scope
- ALGOL introduced blocks to create scopes. Since then, many languages allow shadowing, including C, C++, and Java.
- C# allows some shadowing between an inner and outer class, and between a method and its class, but not across an if-block or switch case labels.
How much shadowing is allowed
- Kotlin lets more forms of shadowing: an inner function can shadow a passed argument, and an inner block can shadow an outer block.
- Java allows some shadowing (for example, a parameter can shadow a class field), but not all forms Kotlin supports.
- Some languages completely disallow shadowing, such as CoffeeScript and V.
- Lua and Python also show shadowing across blocks. In Python, because variables are created by assignment, you use nonlocal (Python 3) to refer to outer, non-global variables, and global to refer to global ones.
- ECMAScript 6 introduces let and const with block scope, which allows shadowing across blocks.
Takeaway
Shadowing can make code harder to read, so many developers prefer clearer, non-overlapping names where possible.
This page was last edited on 3 February 2026, at 01:58 (CET).