0% found this document useful (0 votes)
10 views46 pages

ch5.2-scope

The document discusses the concept of variable scope in programming languages, defining local, nonlocal, and global variables, and explaining static and dynamic scoping. It details how static scope is determined by program text and provides examples from languages like JavaScript and C++. Additionally, it covers the implications of global variables and the differences in scope handling across various programming languages.

Uploaded by

kaankaya928
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views46 pages

ch5.2-scope

The document discusses the concept of variable scope in programming languages, defining local, nonlocal, and global variables, and explaining static and dynamic scoping. It details how static scope is determined by program text and provides examples from languages like JavaScript and C++. Additionally, it covers the implications of global variables and the differences in scope handling across various programming languages.

Uploaded by

kaankaya928
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Concepts of

Programming
Languages

Scope

ISBN 0-321-49362-1
Variable Attributes: Scope

• The scope of a variable is the range of statements


over which it is visible
• Variable is visible in a statement if it can be
referenced in that statement.
• The scope rules of a language determine
 how a particular occurrence of a name is associated with
a variable,
 or in the case of a functional language, how a name is
associated with an expression.
 The scope rules of a language also determine how the
references to variables declared outside the currently
executing subprogram or block are associated with
variables
Copyright © 2015 Pearson. All rights reserved. 1-2
Variable Attributes: Scope…

Definitions
• The local variables of a program unit are those that
are declared in that unit

• The nonlocal variables of a program unit are those


that are visible in the unit but not declared there

• Global variables are a special category of nonlocal


variables

Copyright © 2015 Pearson. All rights reserved. 1-3


Variable Attributes: Scope…

Scope could be
• Static Scope
• Block Structure
• Declaration Order
• Global scope
• Dynamic Scope

• Scope and lifetime

• Referencing environment

Copyright © 2015 Pearson. All rights reserved. 1-4


Static Scope

• Scope of variables can be determined statically


– by looking at the program
– prior to execution

• First defined in ALGOL 60.

• Based on program text to connect a name


reference to a variable,
- You (or the compiler) must find the declaration

Copyright © 2015 Pearson. All rights reserved. 1-5


Static Scope…

• Two categories of static scoped


languages
1. Those in which subprograms can be nested
 Creates nested static scope
 Ada, JavaScript, Common Lisp, Scheme, Fortran
2003+, F#, Python

2. In which subprograms cannot be nested


 C-based languages

Copyright © 2015 Pearson. All rights reserved. 1-6


Static Scope…

• Search process for Nested fn:


-search declarations,
 first locally,
 then in increasingly larger
enclosing scopes,
 until one is found for the
given name

• Enclosing static scopes (to a


specific scope) are called its static
ancestors; the nearest static
ancestor is called a static parent  main is the static parent of p2.
 p2 is the static parent of p1

Copyright © 2015 Pearson. All rights reserved. 1-7


Static Scope: Example (JavaScript)

function big() { big calls sub1


function sub1() { sub1 calls sub2
var x = 7; sub2 uses x
sub2();
}
function sub2() {
var y = x;
}
var x = 3;
sub1();
}

– Static scoping
•Reference to x in sub2 is to big’s x

Copyright © 2015 Pearson. All rights reserved. 1-8


Static Scope: Example (JavaScript)

function big() { big calls sub1


function sub1() { sub1 calls sub2
var x = 7; sub2 uses x
sub2();
}
function sub2() {
var y = x;
}
var x = 3;
sub1();
}

• Variables can be hidden from a unit by having a


"closer" variable with the same name
– Example
•Reference to x in sub1 is to local x
•big‘s x is hidden from sub1
Copyright © 2015 Pearson. All rights reserved. 1-9
Blocks

• Block-structured language:
• Some languages allow new static scopes to be defined in
the midst of executable code.
• It allows a section of code its own local variables whose
scope is minimized.
• Such section of code is called a block

• The variables are typically stack dynamic so they


have their
• storage allocated when the section is entered and
• deallocated when the section is exited

• ALGOL 60 introduced static scopes inside a block

Copyright © 2015 Pearson. All rights reserved. 1-10


Blocks…

– The C- based languages allow local static scopes in


a block
– Example in C:
void sub() {
int count;
while (...) {
int count;
count++;
...
}

}
- Note: legal in C and C++,
- but not in Java and C# - too error-prone
- Nonfunction blocks cannot be defined in JavaScript
Copyright © 2015 Pearson. All rights reserved. 1-11
Static Scope: Example (C++)

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-12
Static Scope: The LET Construct…
• let construct in most functional languages
- Similar to the blocks of the imperative languages
• Most functional languages include some form of let
construct
• A let construct has two parts
– The first part binds names to values
– The second part uses the names defined in the first part
• In Scheme: Example:
(LET ( ( LET (
(name1 expression1) (top (+ab))
… (bottom (-cd))
(namen expressionn)) (/top bottom)
expression )
)

Copyright © 2015 Pearson. All rights reserved. 1-13


Static Scope: The LET Construct…
• In Scheme: Example:
(LET ( ( LET (
(name1 expression1) (top (+ab))
(bottom (-cd))

(/top bottom)
(namen expressionn))
)
expression
)
• Call to let computes and returns the value of the
expression (a + b) / (c – d).
• In Functional Languae
– names are of values (they are not variables like imperative
language)
– their scope is local to the call to LET

Copyright © 2015 Pearson. All rights reserved. 1-14


The LET Construct (continued)

• In ML: let
let val top=a+b
val name1 = expression1 val bottom=c-d
… in
top/bottom
val namen = expressionn
end;
in
expression
end;

Copyright © 2015 Pearson. All rights reserved. 1-15


Declaration Order

• In C89, as well as in some other languages, all data


declarations in at the beginning of a function
- except those in nested blocks
• C99, C++, Java, and C# allow variable declarations to
appear anywhere a statement can appear
– In C99, C++, and Java, the scope of all local variables is from
the declaration to the end of the block

Copyright © 2015 Pearson. All rights reserved. 1-16


Declaration Order: C#

– In C#, the scope of any variable declared in a block is the whole


block, regardless of the position of the declaration in the block,
as long as it is not in a nested block
– C# does not allow the declaration of a variable in a nested block
to have the same name as a variable in a nesting scope.
- a variable still must be declared before it can be used

{ {
int x; …
… {
{ int x; // illegal
int x; // illegal …
… }
} …
… int x;
} }

Copyright © 2015 Pearson. All rights reserved. 1-17


Declaration Order: JavaScript
• Local variables can be declared anywhere in a function,
• but the scope of such a variable is always the entire function.
• If used before its declaration in the function
- such a variable has the value undefined.
- The reference of it is not illegal.

{ {
int x; …
… {
{ int x; // legal
int x; // legal …
… }
} …
… int x;
} }

Copyright © 2015 Pearson. All rights reserved. 1-18


Declaration Order (continued)

• for statements in C++, Java, and C#


– variables can be declared in initialization
expressions
– The scope of such variables is restricted to the
for construct

void fun() {
. . .
for (int count = 0; count < 10; count++){
. . .
}
. . .
}

Copyright © 2015 Pearson. All rights reserved. 1-19


Global Scope

• C, C++, PHP, and Python support a


program structure that consists of a
sequence of function definitions in a file
• Global variables
– These languages allow variable declarations to
appear outside function definitions called global
variables
• A global variable in C is implicitly visible in
all subsequent functions in the file,
– except those that include a declaration of a local
variable with the same name
Copyright © 2015 Pearson. All rights reserved. 1-20
Global Scope…
• C and C++have both declarations (just attributes)
and definitions (attributes and storage)
• Declaration: Specify types and other attributes but
do not cause storage allocation
• Definition: Specify attributes and cause storage
allocation
– A declaration outside a function definition
specifies that it is defined in another file
• A global variable that is defined after a function
can be made visible in the function by declaring it
to be external
- extern int sum;
Copyright © 2015 Pearson. All rights reserved. 1-21
Global Scope: C++ Global Variables

int staticCheck(int any)


{
extern int counter2;
static int counter =0;
counter = counter + any;
counter2++;
return counter;
}

int counter2=8;

int main() {

cout<<counter2<<endl;
cout<<staticCheck(5)<<endl;
cout<<staticCheck(15)<<endl;
cout<<counter2<<endl;
}

Copyright © 2015 Pearson. All rights reserved. 1-22


Global Scope: C++ Global Variables

int counter2=8;

int staticCheck(int any)


{
int counter2;
static int counter =0;
counter = counter + any;
counter2++; //local
return counter;
}

int main() {

cout<<counter2<<endl;
cout<<staticCheck(5)<<endl;
cout<<staticCheck(15)<<endl;
cout<<counter2<<endl;
}
Copyright © 2015 Pearson. All rights reserved. 1-23
Global Scope: C++ Global Variables

int counter2=8; int counter2=8;

int staticCheck(int any) int staticCheck(int any)


{ {
int counter2; int counter2;
static int counter =0; static int counter =0;
counter = counter + any; counter = counter + any;
counter2++; //local ::counter2++; //global
return counter; return counter;
} }

int main() { int main() {

cout<<counter2<<endl; cout<<counter2<<endl;
cout<<staticCheck(5)<<endl; cout<<staticCheck(5)<<endl;
cout<<staticCheck(15)<<endl; cout<<staticCheck(15)<<endl;
cout<<counter2<<endl; cout<<counter2<<endl;
} }
Copyright © 2015 Pearson. All rights reserved. 1-24
Global Scope: C++ Function declaration/
definition
int counter2=8;
int staticCheck(int);

int main() {

cout<<counter2<<endl;
cout<<staticCheck(5)<<endl;
cout<<staticCheck(15)<<endl;
cout<<counter2<<endl;
}

int staticCheck(int any)


{
int counter2;
static int counter =0;
counter = counter + any;
counter2++;
return counter;
}
Copyright © 2015 Pearson. All rights reserved. 1-25
Global Scope (continued)

• PHP
 Variables are implicitly declared when they appear in a
statement
 Global variable: any variable that is implicitly declared
outside any function
 Local variables: variables implicitly declared in functions
 Global variables are not implicitly seen in any function
 Can be made visible in functions in two ways:
1) If a local variable has the same name as global one,
can access global variable via $GLOBALS array
2) If no local variable has the same name include the
global variable using global declaration

Copyright © 2015 Pearson. All rights reserved. 1-26


Global Scope: PHP Global Variables

$day="Monday";
$month= "January";

function calendar()
{
$day = "Tuesday";
global $month;
print "local day is $day \n";
$gday= $GLOBALS['day'];
print "global day is $gday \n";
print "global month is $month ";
}
calendar();

Copyright © 2015 Pearson. All rights reserved. 1-27


Global Scope (continued)

• JavaScript:
• Global variables are similar to PHP
• But no way to access a global variable in a function that
has declared a local variable with the same name

Copyright © 2015 Pearson. All rights reserved. 1-28


Global Scope: Python Global Variable

• 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

day= "Monday"
def calendar():
print ("The global day is:", day)

calendar()

Copyright © 2015 Pearson. All rights reserved. 1-29


Global Scope: Python Global Variable

day= "Monday"
def calendar(): day= "Monday"
print ("The global day is:", day) def calendar():
print ("The global day is:", day)
calendar() day="Tuesday"
print ("The global day is:", day)
calendar()

UnboundLocalError error message:


Illegal Forward reference

Copyright © 2015 Pearson. All rights reserved. 1-30


Global Scope: Python Global Variable

day= "Monday"
def calendar(): day= "Monday"
print ("The global day is:", day) def calendar():
print ("The global day is:", day)
calendar() day="Tuesday"
print ("The global day is:", day)
calendar()

The assignment to day can be to the


global variable if day is declared to be
global at the beginning of the function
Illegal Forward reference
day= "Monday" as day will be a local variable
def calendar():
global day
print ("The global day is:", day)
day="Tuesday"
print ("The global day is:", day)
calendar()

Copyright © 2015 Pearson. All rights reserved. 1-31


Evaluation of Static Scoping

• Works well in many situations


• Problems:
– In most cases, too much access is possible
– As a program evolves, the initial structure is
destroyed and local variables often become
global; subprograms also gravitate toward
become global, rather than nested

Copyright © 2015 Pearson. All rights reserved. 1-32


Dynamic Scope

• Based on calling sequences of program units, not


their textual layout (temporal versus spatial)

• References to variables are connected to


declarations by searching back through the chain
of subprogram calls that forced execution to this
point

• APL, SNOBOL 4, early versions of Lisp.

Copyright © 2015 Pearson. All rights reserved. 1-33


Dynamic Scope…

• To find the correct meaning of a variable


during execution:
1. Search local declarations
2. Search declarations of dynamic parent, calling
function, so on
3. If none found in any dynamic ancestor gives run-
time error

Copyright © 2015 Pearson. All rights reserved. 1-34


Scope Example

function big() { big calls sub1


function sub1() { sub1 calls sub2
var x = 7; sub2 uses x
sub2();
}
function sub2() {
var y = x;
}
var x = 3;
sub1();
}

– Static scoping
•Reference to x in sub2 is to big's x

Copyright © 2015 Pearson. All rights reserved. 1-35


Scope Example
big calls sub1
function big() {
sub1 calls sub2
function sub1() {
sub2 uses x
var x = 7;
sub2();
}
function sub2() {
var y = x;
}
var x = 3;
sub1();
}

– 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-36
Scope Example

function big() { big calls sub2


function sub1() { sub2 uses x
var x = 7;
sub2();
}
function sub2() {
var y = x;
}
var x = 3;
sub2();
}

– Dynamic scoping
•Reference to x in sub2 is to big's x

Copyright © 2015 Pearson. All rights reserved. 1-37


Scope…

• Evaluation of Dynamic Scoping:


– Advantage: convenience
– Disadvantages:
1. While a subprogram is executing, its variables are
visible to all subprograms it calls
2. Impossible to statically type check
3. Poor readability- it is not possible to statically
determine the type of a variable

Copyright © 2015 Pearson. All rights reserved. 1-38


Scope and Lifetime

• Scope and lifetime are sometimes closely


related, but are different concepts
• Consider a static variable in a C or C++
function:
- Statically bound to the scope of the function
- Statically bound to the storage
- But lifetime extends over the entire execution of
the program

Copyright © 2015 Pearson. All rights reserved. 1-39


Scope and Lifetime: Example
int counter2=8;

int staticCheck(int any)


{
static int counter =0;
counter = counter + any;
counter2++;
return counter;
}

int main() {

cout<<counter2<<endl;
cout<<staticCheck(5)<<endl;
cout<<staticCheck(15)<<endl;
cout<<counter2<<endl;
}

Copyright © 2015 Pearson. All rights reserved. 1-40


Scope and Lifetime: Example
int counter2=8;

int staticCheck(int any)


{
 Scope is static and local to the function
static int counter =0;
 Lifetime extends over the entire program execution
counter = counter + any;
counter2++;
return counter;
}

int main() {

cout<<counter2<<endl;
cout<<staticCheck(5)<<endl;
cout<<staticCheck(15)<<endl;
cout<<counter2<<endl;
}

Copyright © 2015 Pearson. All rights reserved. 1-41


Referencing Environments

• The referencing environment of a statement is the


collection of all names that are visible in the
statement

• In a static-scoped language: it is the local variables


plus all of the visible variables in all of the
enclosing scopes

Copyright © 2015 Pearson. All rights reserved. 1-42


Reference Environment: Example

Copyright © 2015 Pearson. All rights reserved. 1-43


Referencing Environments…

• In a dynamic-scoped language, the referencing


environment is the local variables plus all visible
variables in all active subprograms

- A subprogram is active if its execution has begun but has


not yet terminated

Copyright © 2015 Pearson. All rights reserved. 1-44


Reference Environment: Example

void sub1() { Assume that main calls sub2, which


int a, b; calls sub1. What will be the
. . . <------------ 1
} /* end of sub1 */
referencing environment at point 1, 2,
void sub2() { and 3?
int b, c;
. . . . <------------ 2
sub1(); Point Referencing Environment
} /* end of sub2 */ 1 a and b of sub1, c of sub2, d of
void main() { main, (c of main and b of sub2
int c, d; are hidden)
. . . <------------ 3 2 b and c of sub2, d of main, (c of
sub2(); main is hidden)
} /* end of main */ 3 c and d of main

Copyright © 2015 Pearson. All rights reserved. 1-45


Reference Environment: Example

Exercise:
What will be the final values of
variables x, y and a at the end of
execution of the main function
(before retrun) if it is a:
i) Static scoped language
ii) Dynamic scoped language?

Copyright © 2015 Pearson. All rights reserved. 1-46

You might also like