W2 Scope
W2 Scope
– Static scoping
• Reference to x in sub2 is to big's x
int i = 1;
int main() {
i=2;
{
int i=3;
cout << i;
for (i=1; i<=3; i++) {
cout << i;
}
cout << i;
}
cout << i;
for (i=3; i<=5; i++) {
cout << i;
}
cout << i;
}
1-5
Scope (continued)
• In ML:
let
val name1 = expression1
…
val namen = expressionn
in
expression
end;
• Python
– A global variable can be referenced in functions,
but can be assigned in a function only if it has
been declared to be global in the function
– Static scoping
• Reference to x in sub2 is to big's x
– Static scoping
• Reference to x in sub2 is to big's x
– Dynamic scoping
• Reference to x in sub2 is to sub1's x
•
Copyright © 2015 Pearson. All rights reserved. 1-17
Scope Example