开发者

Question about Static and Dynamic Scoping Problem

开发者 https://www.devze.com 2023-02-21 19:40 出处:网络
Can you confirm my answer for the following code: procedure main var x,y,z; p开发者_开发知识库rocedure sub1

Can you confirm my answer for the following code:

procedure main
var x,y,z;

    p开发者_开发知识库rocedure sub1
       begin
        var x,z 
        x := 6;
        z := 7;
        sub2();
        x := y*z + x;
        print(x);       
      end
    procedure sub2
      begin
        var x,y
        x := 1;
        y := x+z+2;
        print(y);       
      end
begin
    x := 1; y:=3; z:=5;
    sub1();
    sub2();
end 

I got:

  • static:

    8
    27
    
  • dynamic:

    10
    27
    

Is that correct?


If Pascal supported dynamic scoping, then your analysis would be correct, as far as it goes. The z variable declared in sub1 would shadow the one declared in main, even within sub2. But the x declared in sub2 would not affect the value of the x declared in sub1, so sub1 still uses the original value 6 when it reads x after calling sub2.

Your analysis is incomplete, though. There should be three values printed each time, not just two. The third value printed should be 8 in both cases.


I've no idea what static vs dynamic means. Pascal always uses the variable in the innermost scope. If you use that, then 8,27 is the result. I don't know how you came to the other result (everything global?)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号