Lexical scoping vs dynamic scoping

2020-02-10 07:39发布

问题:

So I have this problem where I have to figure out the output using two different scoping rules. I know the output using lexical scoping is a=3 and b=1, but I am having hard time figure out the output using dynamic scoping.
Note:the code example that follows uses C syntax, but let's just treat it as pseudo-code.

int a,b;

int p() {
    int a, p;
    a = 0; b = 1; p = 2;
    return p;
}

void print() {
    printf("%d\n%d\n",a,b);
}

void q () {
    int b;
    a = 3; b = 4;
    print();
}

main() {
    a = p();
    q();
}

Here is what I come up with. Using Dynamic scoping, the nonlocal references to a and b can change. So I have a=2 ( return from p() ), then b=4 ( inside q() ). So the output is 2 4?

回答1:

As we know, C doesn't have dynamic scoping, but assuming it did, the program would print 3 4.

In main, a and b are the global ones. a will be set to 2, as we will see that this is what p will return.

In p, called from main, b is still the global one, but a is the one local in p. The local a is set to 0, but will soon disappear. The global b is set to 1. The local p is set to 2, and 2 will be returned. Now the global b is 1.

In q, called from main, a is the global one, but b is the one local in q. Here the global a is set to 3, and the local b is set to 4.

In print, called from q, a is the global one (which has the value 3), and b is the one local in q (which has the value 4).

It is in this last step, inside the function print, that we see a difference from static scoping. With static scoping a and b would be the global ones. With dynamic scoping, we have to look at the chain of calling functions, and in q we find a variable b, which will be the b used inside print.



回答2:

C is not a dynamically scoped language. If you want to experiment in order to understand the difference, you're better off with a language like Perl which lets you chose between both.