Home > Web Front-end > JS Tutorial > Lexical vs. Dynamic Scoping: What's the Difference and Why Do We Prefer Static Scoping?

Lexical vs. Dynamic Scoping: What's the Difference and Why Do We Prefer Static Scoping?

Patricia Arquette
Release: 2024-12-09 16:15:15
Original
515 people have browsed it

Lexical vs. Dynamic Scoping: What's the Difference and Why Do We Prefer Static Scoping?

Lexical Scoping: A Detailed Explanation

Understanding lexical scoping can be simplified through examples.

Lexical Scoping (Static Scope)

In lexical scoping, every inner level can access its outer levels. An example in C-like syntax:

void fun() {
    int x = 5;

    void fun2() {
        printf("%d", x);
    }
}
Copy after login

Dynamic Scoping

Dynamic scoping allows inner levels to access variables from dynamically determined outer scopes, depending on the call chain. A C-like syntax example:

void fun() {
    printf("%d", x);
}

void dummy1() {
    int x = 5;

    fun();
}

void dummy2() {
    int x = 10;

    fun();
}
Copy after login

Here, fun can access x from either dummy1 or dummy2, or any other function that calls fun with x declared within it.

dummy1(); // Prints 5
dummy2(); // Prints 10
Copy after login

Key Differences

Static scoping can be determined at compile-time, while dynamic scoping depends on the runtime call chain. Dynamic scoping is like passing references of all variables to the called function.

Why Use Static Scoping?

Static scoping is often preferred because it simplifies comprehension. Most languages, including Lisp, eventually adopted this approach. Dynamic scoping can introduce complexity when the call chain is dependent on runtime conditions.

The above is the detailed content of Lexical vs. Dynamic Scoping: What's the Difference and Why Do We Prefer Static Scoping?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template