GeeksforGeeks App
Open App
Browser
Continue

# Static and Dynamic Scoping

The scope of a variable x in the region of the program in which the use of x refers to its declaration. One of the basic reasons for scoping is to keep variables in different parts of the program distinct from one another. Since there are only a small number of short variable names, and programmers share habits about naming of variables (e.g., I for an array index), in any program of moderate size the same variable name will be used in multiple different scopes.
Scoping is generally divided into two classes:
1. Static Scoping
2. Dynamic Scoping
Static Scoping:
Static scoping is also called lexical scoping. In this scoping, a variable always refers to its top-level environment. This is a property of the program text and is unrelated to the run-time call stack. Static scoping also makes it much easier to make a modular code as a programmer can figure out the scope just by looking at the code. In contrast, dynamic scope requires the programmer to anticipate all possible dynamic contexts.
In most programming languages including C, C++, and Java, variables are always statically (or lexically) scoped i.e., binding of a variable can be determined by program text and is independent of the run-time function call stack.
For example, the output for the below program is 10, i.e., the value returned by f() is not dependent on who is calling it (Like g() calls it and has a x with value 20). f() always returns the value of global variable x.

## C

 `// A C program to demonstrate static scoping.``#include``int` `x = 10;` `// Called by g()``int` `f()``{``   ``return` `x;``}` `// g() has its own variable``// named as x and calls f()``int` `g()``{``   ``int` `x = 20;``   ``return` `f();``}` `int` `main()``{``  ``printf``(``"%d"``, g());``  ``printf``(``"\n"``);``  ``return` `0;``}`

Output :

`10`

To sum up, in static scoping the compiler first searches in the current block, then in global variables, then in successively smaller scopes.
Dynamic Scoping:
With dynamic scope, a global identifier refers to the identifier associated with the most recent environment and is uncommon in modern languages. In technical terms, this means that each identifier has a global stack of bindings and the occurrence of an identifier is searched in the most recent binding.
In simpler terms, in dynamic scoping, the compiler first searches the current block and then successively all the calling functions.

## C

 `// Since dynamic scoping is very uncommon in``// the familiar languages, we consider the``// following pseudo code as our example. It``// prints 20 in a language that uses dynamic``// scoping.  ` `int` `x = 10;` `// Called by g()``int` `f()``{``   ``return` `x;``}` `// g() has its own variable``// named as x and calls f()``int` `g()``{``   ``int` `x = 20;``   ``return` `f();``}` `main()``{``  ``printf``(g());``}`

Output in a language that uses Dynamic Scoping :

`20`

Static Vs Dynamic Scoping
In most programming languages static scoping is dominant. This is simply because in static scoping it’s easy to reason about and understand just by looking at code. We can see what variables are in the scope just by looking at the text in the editor.
Dynamic scoping does not care about how the code is written, but instead how it executes. Each time a new function is executed, a new scope is pushed onto the stack.
Perl supports both dynamic and static scoping. Perl’s keyword “my” defines a statically scoped local variable, while the keyword “local” defines a dynamically scoped local variable.

## Perl

 `# A perl code to demonstrate dynamic scoping``\$x` `= 10;``sub` `f``{``   ``return` `\$x``;``}``sub` `g``{``   ``# Since local is used, x uses``   ``# dynamic scoping.``   ``local` `\$x` `= 20;` `   ``return` `f();``}``print` `g().``"\n"``;`

Output :

`20`

### Static Scoping:

• It is easy to reason about the scope of variables in a program, because it is determined at compile-time.

• It can lead to faster execution because the scope of variables can be determined at compile-time, which eliminates the need for runtime lookups.

• It is less error-prone because variables can only be accessed within their defined scope.
• Since static scoping enables the compiler to determine the scope of variables at compile-time, it can optimize the code by eliminating unnecessary variable lookups.
• The elimination of runtime lookups due to static scoping can result in faster program execution, leading to improved program performance.
• Static scoping prevents accidental or intentional modification of variables outside their scope, making the program safer to execute.
• Since static scoping makes it easier to reason about the scope of variables in a program, it can make program maintenance and debugging less time-consuming and less error-prone.

• It can be more difficult to write and debug programs because the scope of variables can be less flexible.

• It can be harder to write code that is reusable, because variables can only be accessed within their defined scope.
• Static scoping is not well-suited for implementing dynamic features such as dynamic scoping or closures, which require a more flexible approach to variable scoping.
•  Static scoping can make it harder to achieve encapsulation, a fundamental principle of object-oriented programming. Encapsulation allows for better code organization, improved code readability, and easier code maintenance.
• Static scoping can lead to namespace collisions, where variables in different scopes have the same name, leading to confusion and errors.

### Dynamic Scoping:

• It is more flexible, because variables can be accessed from any part of the program.

• It can be easier to write code that is reusable, because variables can be accessed from anywhere.
• Dynamic scoping can make it easier to debug certain types of code, such as recursive functions or code with complex control flow. This is because variables can be accessed from any part of the program, making it easier to track their values and behavior.
• It allows code to adapt more easily to changing requirements or circumstances. This is because variables can be accessed from anywhere in the program, enabling greater flexibility in variable scoping.