问题
I'm working on this problem and I got the answers :
Statically: 20, 16
Dynamically: 20, 100
is that correct?
Consider the program below (in a Pascal like language). What is the output of the language is statically scoped? What is the output if the language is dynamically scoped?
Program main;
x: integer;
procedure f1(z: integer)
begin
return z * x;
end
procedure f2(z: integer)
int x;
begin
x = 2;
return f1(z) * x;
end
begin /* main program */
x = 5;
print f1(4);
print f2(4);
end
回答1:
Why not try out both versions? Using Perl with static scope:
my $x = 5;
sub f1($) {
my $z = shift;
return $z * $x;
}
sub f2($) {
my $z = shift;
my $x = 2;
return f1($z) * $x;
}
print f1(4), "\n";
print f2(4), "\n";
I get 20, 40. (20 being 4 * 5, 40 being (4 * 5) * 2.)
Replacing all the mys with locals to get dynamic scope, I get 20, 16. (20 being 4 * 5, 16 being (4 * 2) * 2.)
Unfortunately, since you only posted your conclusions, no explanation, I can't point out where you went wrong . . .
来源:https://stackoverflow.com/questions/9421863/statically-and-dynamically-scopes