Вы находитесь на странице: 1из 66

Lecture Outline

• Variables
1. Name
• Case sensitive, Keyword, Reserved word
2. Address
• l-value
3. Value
• r-value, Named constants
4. Type
• Static type binding, Dynamic type binding, Type checking,
Coercion, Strong typing
5. Lifetime
• Static variables, Stack-dynamic variables, Explicit heap dynamic
variables, Implicit heap dynamic variables
6. Scope
• Static scope, Dynamic scope, Referencing environments
– Note: Lecture notes are based on Robert W. Sebesta’s Concepts of
1
Programming Languages, 4th Edition
Introduction
• Imperative languages are abstractions of
von Neumann architecture
– Memory
– Processor
• Variables are abstractions of memory cells

2
Variables
• Variables have six basic attributes
1. Name
2. Address
3. Value
4. Type
5. Lifetime
6. Scope

3
Variables
• 1. Name
– Not all variables have them
– Can have a nameless (anonymous) memory
cells
• Explicit heap-dynamic variables
• Only referenced through pointer or reference
variables

4
Names
• Design issues for names
– Maximum length?
– Are names case sensitive?
– Are special words reserved words or keywords?

5
Names
• Length
– If too short, they cannot be descriptive
– Language examples
• FORTRAN I: maximum 6
• COBOL: maximum 30
• FORTRAN 90 and ANSI C: maximum 31
• Ada and Java: no limit, and all are significant
• C++: no limit, but implementers often impose one

6
Names
• Case sensitivity
– Disadvantage: readability
– Names that look alike are actually different
• BigVariable & bigVariable & bigvariable
– C, C++, and Java names are case sensitive
– The names in most other languages are not

7
Names
• Restrictions:
– keywords have special meaning (e.g. ‘for’)
– reserved words cannot be used as names
– generally keywords are reserved

8
Names
• Special words
– Keyword
• A word that is special only in certain contexts
• Disadvantage: poor readability
• Fortran’s Real can be used to declare a variable, but
also as a variable itself
– Reserved word
• A special word that cannot be used as a user-defined
name
• C’s float can be used to declare a variable, but not as a
variable itself
9
Class Discussion
• Decide what to the following identifier
forms is most readable, and then support that
decision
1. SumOfSales
2. sum_of_sales
3. SUMOFSALES

10
Variables
• 2. Address
– The memory address with which the variable is
associated
– Also called l-value, because it is what is
required when a variable is on the left side of an
assignment equation

11
Variables
• 2. Address
• A given name can be associated with
multiple addresses during program
execution (e.g. parameters of a recursive
function, an instance variable defined in a
multiply-instantiated class).
• Aliasing occurs when many variables share
an address.
12
How aliases can be created:

• Pointers, reference variables, Pascal


variant records, C and C++ unions,
and FORTRAN EQUIVALENCE
• Some of the original justifications for
aliases are no longer valid; e.g. memory
reuse in FORTRAN
- replace them with dynamic allocation
13
Variables
• 3. Value
– The contents of the location with which the
variable is associated
– Also called the r-value because it is what is
required when the variable is used on the right
hand side of an assignment statement
– Abstract memory cell
• The physical cell or collection of cells associated
with a variable

14
Variables
• 3. Value
• In C the binding of a set of value to types is
left to implementation time.
– different implementations can (and do) make
different decisions
– implication is that the very same program can
behave differently on different platforms.

15
Named Constants
• Named constant
– A variable that is bound to a value only when it
is bound to storage
– Its value cannot be changed later in the program
– Advantages: readability and modifiability
– C example
#define PI 3.141519

16
Variables
• 4. Type
– Determines the range of values of variables
– And the set of operations that are defined for
values of that type
– In Java, int type
• Value range of -2,147,483,648 to 2,147,483,647
• Operations addition, subtraction, multiplication,
division, and modulus

17
The Concept of Binding
• A binding is an association, such as
between an attribute and an entity, or
between an operation and a symbol
– Binding time is the time at which a binding
takes place.

18
The Concept of Binding
• Static type binding
– First occurs before run time
– Remains unchanged throughout program
execution
• Dynamic type binding
– First occurs during execution
– Can change during execution of the program

19
Static Type Binding
• Explicit declaration
– A program statement used for declaring the
types of variables
• Implicit declaration
– A default mechanism for specifying types of
variables (the first appearance of the variable in
the program)
• FORTRAN, PL/I, BASIC, and Perl provide
implicit declarations
– Advantage: writability
– Disadvantage: reliability (less trouble with Perl)20
Perl Variables
• Scalar variable
– Begin with a $
– Can be a string or numeric
• $var1 = 9;
• $var2 = 'string';
• Array variable
– Begin with a @
• @fruits=("apples","pears","kumquats");
• $fruits[2] returns kumquats
• Associative array variable (hash structure)
21
– Begin with a %
Dynamic Type Binding
• Specified through an assignment statement
– JavaScript and PHP
– For example, in JavaScript
list = [2, 4.33, 6, 8];
list = 17.3;
– Advantage: flexibility (generic program units)
– Disadvantages:
• High cost (dynamic type checking and interpretation)
• Type error detection is difficult
• Must be implemented by a pure interpreter 22
Type inferencing (ML)
• (Milner et al., 1990)
• ML derives the types of all expressions
from the types of their constituent parts.
• ML (with very few exceptions) does not
require any type declarations, and yet all
expressions are fully typed at compile time.
• ML uses type variables to express generic
types (e.g. ’a and ”a).
23
Type Checking
• Type checking
– The activity of ensuring that the operands of an operator are
of compatible types
• Compatible type
– One that is either legal for the operator, or is allowed under
language rules to be implicitly converted, by compiler-
generated code, to a legal type
– This automatic conversion is called a coercion

24
Type Checking
• Compatible type
• Automatic Conversion
int a; float b; a = b;
• Explicit Conversion (Casting)
int a, b; float c; c = (float)a/(float) b;
• Type error
– The application of an operator to an operand of an
inappropriate type

25
Type Checking
• A programming language is strongly typed
if type errors are always detected
– If all type bindings are static, nearly all type
checking can be static
– If type bindings are dynamic, type checking
must be dynamic

26
Strong Typing
• Advantage of strong typing
– Allows the detection of the misuses of variables that
result in type errors
• Language examples
– C and C++ are not
• Unions are not type checked
– Ada is, almost
• UNCHECKED CONVERSION is loophole
– Java & C# are (similar to Ada)

27
Strong Typing
• Coercion rules strongly affect strong typing
– They can weaken it considerably (C++ versus
Ada)
– Although Java has just half the assignment
coercions of C++, its strong typing is still far
less effective than that of Ada

28
Variables
• 5. Lifetime
– The lifetime of a variable is the time during
which it is bound to a particular memory cell
• Allocation - getting a cell from some pool of
available cells
• Deallocation - putting a cell back into the pool

29
The Concept of Binding
• Categories of variables by lifetimes
1. Static variables
2. Stack-dynamic variables
3. Explicit heap dynamic variables
4. Implicit heap dynamic variables

30
Memory organization
STATIC
code &
static data
STACK
local data:
invocation records

AVAILABLE
MEMORY

HEAP
dynamic data

31
static variables
• Bound to a memory location prior to
execution.
• No run-time allocation needs to occur:
efficient.
• Persistent: variable persists throughout
execution of a program.

32
#include “stdio.h”; Example (C)
int counter() {
static int k = 0;
return ++k;
}
int main() {
printf(“Counter is %d \n”,counter());
printf(“Counter is %d \n”,counter());
return 0;
}

/* OUTPUT IS:
Counter is 1
Counter is 2
*/ 33
Notes about example
• static variable k is allocated space in the
static segment
• allocation happens once
• k’s lifetime is the that of the entire program
• k’s value persists from call to call

34
stack dynamic variables
• “storage bindings are created when their
declaration statements are elaborated, but
whose types are statically bound”
• Allocated on the run-time stack

35
#include “stdio.h”; Example (C)
int counter() {
int k = 0;
return ++k;
}
int main() {
printf(“Counter is %d \n”,counter());
printf(“Counter is %d \n”,counter());
return 0;
}

/* OUTPUT IS:
Counter is 1
Counter is 1
*/ 36
Notes about example
• stack-dynamic variable k is allocated space
in the stack segment
• allocation happens each time function is
called
• k’s lifetime is the that of the function
invocation
• k’s value does not persist from call to call:
it is reinitialized on each function execution
37
explicit heap-dynamic variables
• anonymous (nameless) variables created at
runtime, allocated on the heap, and
accessible only via indirection (a pointer)
• Example
int *intnode; // Create a pointer
...
intnode = new int; // Create the heap-dynamic variable
...
delete intnode; // Deallocate the heap-dynamic
variable
// to which intnode points
38
public class Count
private int k; Example (Java)
public Count() {
k = 0;
}
public int counter() {
return ++k;
}
public static void main(String [] args) {
Count c = new Count();
System.out.println(“Counter is ”+c.counter());
System.out.println(“Counter is ”+c.counter());
}
}
/* OUTPUT IS:
Counter is 1
Counter is 2
*/

39
Notes about example
• instance variable k is allocated space in the heap
segment
• allocation happens each time object is created
• k’s lifetime is the that of its object
• k’s value persists from call to call of the method
• many different independent k’s can co-exist

40
implicit heap-dynamic variables
• automatic heap-allocation
• JavaScript, [pg. 214]:
list = [10.2, 3.5];
list = 47;
• Scheme
– all allocation is done on heap
– cons allocates a pair
– environments are allocated on heap (so no
runtime stack is needed for function calls).
41
(define count1
(lambda () Example (Scheme)
(let ((k 0))
(set! k (+ k 1))
k
)))
(define count2
(let ((k 0))
(lambda ()
(set! k (+ k 1))
k
)))
(display (count1)) (newline)
(display (count1)) (newline)
(display (count2)) (newline)
(display (count2)) (newline)
/* OUTPUT IS:
1
1
1
2
*/
42
The Concept of Binding
• Static variables
– Bound to memory cells before execution begins
and remains bound to the same memory cell
throughout execution.
• All FORTRAN 77 variables, C static variables
• Advantages
– Efficiency (direct addressing), history-sensitive
subprogram support
• Disadvantage
– Lack of flexibility (no recursion) 43
The Concept of Binding
• Stack-dynamic variables
– Storage bindings are created for variables when their
declaration statements are elaborated
• Elaboration means that allocation and binding occurs
when execution reaches that code (during runtime)
– These variables are allocated from the runtime stack
• Local variables in C subprograms and Java methods

44
The Concept of Binding
• Stack-dynamic variables
• Advantage
– Allows recursion, conserves storage
• Disadvantages
– Overhead of allocation and deallocation
– Subprograms cannot be history sensitive
– Inefficient references (indirect addressing)

45
Heap
• In programming, heap refers to a common
pool of memory that is available to the
program. The management of the heap is
either done by the applications themselves,
allocating and deallocating memory as
required, or by the operating system or
other system program.

46
The Concept of Binding
• Explicit heap-dynamic
– Allocated and deallocated by explicit directives,
specified by the programmer, which take effect
during execution
– These variables are allocated from the heap
– Referenced only through pointers or references
• Dynamic memory allocation in C (via malloc & free)
• Dynamic objects in C++ (via new & delete)
• All objects in Java
47
The Concept of Binding
• Explicit heap-dynamic variables
• Advantage
– Provides for dynamic storage management
• Can be used to create dynamic structures, such as linked
lists and trees
• Disadvantage
– Difficult to implement correctly

48
The Concept of Binding
• Implicit heap-dynamic variables
– Allocation and deallocation caused by assignment
statements
– All variables in APL
– All strings and arrays in Perl and JavaScript
• Advantage: flexibility
• Disadvantages
– Inefficient, because all attributes are dynamic
– Loss of error detection
49
Variables
• 6. Scope
– The scope of a variable is the range of
statements over which it is visible
• The nonlocal variables of a program unit are those
that are visible but not declared there
• The scope rules of a language determine how
references to names are associated with variables

50
Scope
• Static scope
– Based on program text
– To connect a name reference to a variable, you
(or the compiler) must find the declaration
– Search process
• 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 51
Scope
• Variables can be hidden from a unit by
having a "closer" variable with the same
name
– C++ and Ada allow access to these "hidden"
variables
• In Ada: unit.name
• In C++: class_name::name

52
Scope
• Blocks
– A method of creating static scopes inside program units
– From ALGOL 60
– Examples
C and C++: for (...)
{
int index;
...
}
Ada: declare TEMP : FLOAT;
begin
...
end
53
Scope
• Evaluation of Static Scoping
– Consider the example:
Assume MAIN calls A and B
A calls C and D
B calls A and E

54
Static Scope Example

MAIN MAIN
A

C
A B
D
C D E
B

55
Static Scope Example

MAIN MAIN

A B A B

C D E C D E

56
Static Scope
• Suppose the specification is changed so that
D must now access some data in B
– Solutions
• Put D in B (but then C can no longer call it and D
cannot access A's variables)
• Move the data from B that D needs to MAIN (but
then all procedures can access them)
– Same problem for procedure access
– Overall: static scoping often encourages many
globals
57
Scope
• 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

58
Scope Example
MAIN
- declaration of x
SUB1
- declaration of x -
...
call SUB2 MAIN calls SUB1
...
SUB1 calls SUB2
SUB2 uses x
SUB2
...
- reference to x -
...

...
call SUB1

59
Scope Example
• Static scoping
– Reference to x is to MAIN's x
• Dynamic scoping
– Reference to x is to SUB1's x
• Evaluation of Dynamic Scoping
– Advantage: convenience
– Disadvantage: poor readability

60
Examples comparing
static and dynamic
scope

• Example in C-like language

61
Dynamic vs. static scope:
C-like language
int a = 3;
void foo(){ printf(“a has value %d \n”,a); }
void bar(){ int a = 5; foo();}
foo(); // what does this print?
bar(); // what does this print?

62
With static scope
int a = 3;
void foo(){ printf(“a has value %d \n”,a); }
void bar(){ int a = 5; foo();}
void abc(){ int a = 7; foo();}
foo(); // what does this print?
bar(); // what does this print?
abd(); // what does this print?

C is statically scoped, so the output will be:


a has value 3
a has value 3
a has value 3
63
With dynamic scope
int a = 3;
void foo(){ printf(“a has value %d \n”,a); }
void bar(){ int a = 5; foo();}
void abc(){ int a = 7; foo();}
foo(); // what does this print?
bar(); // what does this print?
abd(); // what does this print?

If C were dynamically scoped, the output would be:


a has value 3
a has value 5
a has value 7
64
Languages with dynamic scope
• Common Lisp and Perl give the
programmer the option of using either
dynamic or static scope.

65
Scope Example in Perl
• See example Perl program scope.pl
– $x = 1;
• default = global scope (a kind of static scope) = visible
throughout program
– my $y = 2;
• my = lexical scope (a kind of static scope) = visible only inside
its block
– local $z = 3;
• local = dynamic scope = visible inside its block and any
subroutines called from that block
– Note that value of dynamic scope variable ($z) will
depend on the order of the subroutine calls
66

Вам также может понравиться