Lexical scoping vs dynamic scoping

后端 未结 2 518
情深已故
情深已故 2020-12-17 01:08

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

相关标签:
2条回答
  • 2020-12-17 01:48

    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.

    0 讨论(0)
  • 2020-12-17 01:51

    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.

    0 讨论(0)
提交回复
热议问题