Sunteți pe pagina 1din 79

CS212: Principles of Programming Languages

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Unit-III Procedures

Subprogram: Simple Call Subprogram, Recursive Subprogram, Static And


Dynamic Scope, Referencing Environment (Local, Non-Local and
Global)

Parameter Passing: Parameter Passing Methods, Dynamic Scope of Variables

Activation Records: Control Flow between Activations, Elements


of Activation Records

PRINCIPLES OF PROGRAMMING LANGUAGES 2


Subprogram
Subprogram : A program separate from the main program that executes a series of
operations/instructions that occurs multiple times during the program cycle.
Subprogram : describes the interface to and the actions of the subprogram abstraction.
Subprogram call : is the explicit request that the called subprograms be executed.
A subprogram declaration provides the protocol, but not the body, of the subprogram.
The two fundamental types of the subprograms are:
 Procedures
 Functions

PRINCIPLES OF PROGRAMMING LANGUAGES 3


A subprogram header
(protocall)
A subprogram header is the first line of the definition, serves several
definitions:
 It specifies that the following syntactic unit is a subprogram definition of some
particular kind.
 The header provides a name for the subprogram.
May optionally specify a list of parameters.
Consider the following header examples:
Fortran ::-Subroutine Adder (parameters)
Ada ::-procedure Adder (parameters)
C ::-void Adder (parameters)

PRINCIPLES OF PROGRAMMING LANGUAGES 4


Implementing “Simple” Subprograms Call

1. Save the execution status of the caller


2. Pass parameters
3. Pass the return address to the callee
4. Transfer control to the callee

PRINCIPLES OF PROGRAMMING LANGUAGES 5


General subprogram characteristics:
Each subprogram has a single entry point

The calling program unit is suspend during The execution


of the called subprogram, which means that there is only one
subprogram in execution at any time

Control always return to the caller when the subprogram


execution terminates

PRINCIPLES OF PROGRAMMING LANGUAGES 6


Design issue of subprogram
What parameter passing method use ?
Are the type of the actual parameter checked against the formal parameter ?
Are local variables statically or dynamically allocated?
If subprogram can be passed as parameters what is the referencing
environment of such subprogram ?
Can subprogram be overloaded ?
Can subprogram be generic ?
Is either separate or independent compilation possible ?

PRINCIPLES OF PROGRAMMING LANGUAGES 7


Examples of procedures

Program example Specification


Program example2 ;
procedure add;
Var
var
x : integer ;
x : integer ; y : integer ;
y : integer ;
Procedure add ( a : integer ; b : integer );
begin BODY begin
read ( x , y ); write ( a + b );
end;
write ( x + y );
end; BEGIN
BEGIN
x = 10 ;
y=5;
add; add ( 10 , 5 ) ;
END . END.

PRINCIPLES OF PROGRAMMING LANGUAGES 9


Function
Functions : structurally resemble procedure, But are semantically modeled
on mathematical functions ( Functions are procedures which return value).
Function are called by appearances of their name in expressions.
In function body The return statement end the execution of the function and
return the value of the expression enclosed in the braces as a result
The function body can contain any number of return statement

e.g: (function header and call )


void sort (int list[], int listlen); // function header

Sort(scores,100); // function call

PRINCIPLES OF PROGRAMMING LANGUAGES 10


Functions :

// function example :

Function minimum ( A,B : Integer) return integer is

Begin

If A<= B then

Return A ;

Else

Return B ;

End if ;

End minimum;

PRINCIPLES OF PROGRAMMING LANGUAGES 11


Subprogram Control Flow

PRINCIPLES OF PROGRAMMING LANGUAGES 12


Parameter Passing
A formal parameter A variable and its type as they appear in the prototype of
the function or method.
An actual parameter The variable or expression corresponding to a formal
parameter that appears in the function or method call in the calling environment
Parameter passing methods are the ways in which parameters are transmitted to
and/or from calling subprogram,
Formal parameters are characterized by one of three distinct semantics
models :
IN: Passes info from caller to callee.
OUT: Callee writes values in caller.
IN/OUT: Caller tells callee value of variable, which may be updated by callee.

PRINCIPLES OF PROGRAMMING LANGUAGES 13


Graph for parameter passing methods :

PRINCIPLES OF PROGRAMMING LANGUAGES 14


Implementation models for parameter passing :

Pass by value
Pass by result
Pass by value result
Pass by reference
Pass by name

PRINCIPLES OF PROGRAMMING LANGUAGES 15


Pass by value

When parameter is passed by value, the value of the actual parameter is used
to initialize the corresponding formal parameter, which then act as a local
variable in the subprogram
Pass by value is some times call pass by copy
Advantage: simple mechanism, actual parameter can be expression or values,
(formal parameters are write protected) does not cause side effect.
Disadvantage: needs additional storage for formal parameters.

PRINCIPLES OF PROGRAMMING LANGUAGES 16


Example
The program below illustrates what happens when arguments are passed by value. A tracing of the
changes in the program’s variables is shown on the right.
int multiply (int, int);

int main() a b c x y
{ 2 5 10 2 5
int a, b, c;
a = 2; 50 10 10
b = 5;
c = multiply(a,b); 5
a = multiply(b,c);
return 0;
50
}

int multiply (int x, int y) When the program ends, the variables
{ remaining in memory have the values
x = x * y; shown in red
return x;
}
PRINCIPLES OF PROGRAMMING LANGUAGES 17
Limitations of pass by value
Recall that a function can have either one return value or no
return value

If we want a function’s action to affect more than one


variable in the calling function, we can’t achieve this goal using
return value alone – remember, our options are one or none

PRINCIPLES OF PROGRAMMING LANGUAGES 18


Example – swap function
Write a function that swaps two values: that is, value a is replaced by value b, and
value b is replaced by the original value of a.

void swap (int x, int y) The function appears to work correctly. The next step is to
{ write a program that calls the function so that we can test it:
int tmp = x;
x = y;
y = tmp; int main()
} {
int a=2, b=6;
cout << “Before swap, a=” << a << “ and b=”
Output: << b << endl;
Before swap, a=2 and b=6 swap(a,b);
After swap, a=2 and b=6 cout << “After swap, a=” << a << “ and b=”
<< b << endl;
return 0;
}
PRINCIPLES OF PROGRAMMING LANGUAGES 19
What went wrong?
In the swap function, parameters x and y were passed the
values of variables a and b via the function call swap(a, b);
Then the values of x and y were swapped
When the function returned, x and y were no longer in
memory, and a and b retained their original values
Remember, when you use pass by value, the parameter only
gets a copy of the corresponding argument; changes to the
copy don’t change the original.

PRINCIPLES OF PROGRAMMING LANGUAGES 20


Pass by reference
In pass by reference method transmits an access path, usually just an address, to the called
subprogram
The called subprogram is allowed to access the actual parameter in the calling program unit.
The advantage of Pass by reference
Passing process is efficient, in term of both time and space, duplicate space is not required, nor is any
copying required
The disadvantage of Pass by reference
Access to the formal parameters will be slower, because of the additional level of indirect addressing that is
required
If only one way communication to the called subprogram is required, inadvertent and erroneous changes may
be made to the actual parameter
The aliases can be created

PRINCIPLES OF PROGRAMMING LANGUAGES 21


Example
Program on the left – return value
Program on the right - a void function with an extra reference parameter.
int multiply (int, int); void multiply (int, int, int *);
int main() int main()
{ {
int a, b, c; int a, b, c;
a = 2; a = 2;
b = 5; b = 5;
c = multiply(a,b); multiply(a,b,&c);
a = multiply(b,c); multiply(b,c,&a);
return 0; return 0;
} }

int multiply (int x, int y) void multiply (int x, int y, int *z)
{ {
x = x * y; *z = x * y;
return x; }
}

PRINCIPLES OF PROGRAMMING LANGUAGES 22


Pass by name
The actual parameter is textually substituted for the formal parameter in all
its occurrences in the subprogram.
Thunk: A thunk is the code which computes the L-value and R-value of an
argument.
Advantage:
More flexible than other methods.
Disadvantage :
Relatively slow than other methods
Very expensive

PRINCIPLES OF PROGRAMMING LANGUAGES 23


Pass by result
Formal parameter acts as local variable just before control returns to caller, value is passed
to actual parameter, which must be a variable
problem #1:
Actual parameter collision, such as call sub(p1, p1) may return different values to p1
depending on order of assignment
Problem #2:
Address evaluation may be done at call or at return, for example list[index] if the index is
changed by the subprogram, either through global access or as formal parameter, then the
address of list[index] will changed between the call and the return

PRINCIPLES OF PROGRAMMING LANGUAGES 24


Pass by value result
The value of the actual parameter is used to initialize the corresponding formal parameter,
the value of the formal parameter is transmitted back to the actual parameter

Pass by value result share with pass by value and pass by result the disadvantage of
requiring multiple storage for parameters and time for copying values.

Pass by value result share with pass by result the problems associated with the order in
which actual parameters are assigned.

PRINCIPLES OF PROGRAMMING LANGUAGES 25


Parameter-Passing Methods for Major
languages
In most language parameter communication takes place thru the run-time stack
Pass-by-reference are the simplest to implement; only an address is placed in the stack
A subtle but fatal error can occur with pass-by-reference and pass-by-value-result: a formal parameter
corresponding to a constant can mistakenly be changed.
C
Pass-by-value
Pass-by-reference is achieved by using pointers as parameters
C++
A special pointer type called reference type for pass-by-reference
Java
All parameters are passed are passed by value
Object parameters are passed by reference

Principles of Programming Languages 1-26


Pass by Value
Example AR for caller 2
AR for callee 2 -> 3
Pass by Result
void caller() AR for caller 2 -> 3
{ AR for callee 3 (initial a = garbage
int a = 2; value)
callee(a); Pass by Value - Result
} AR for caller 2 -> 3
AR for callee 3
void callee(int a) Pass by name
{ AR for caller 2
AR for callee 2 -> 3
a = 3;
}

PRINCIPLES OF PROGRAMMING LANGUAGES 27


Example of call by value versus call by name
begin
integer n;
procedure p(k:
integer);
begin
print(k);
n := n+10;
print(k);
n := n+5;
print(k);
end; Output:
n := 0; call by value: 1 1 1
p(n+1); call by name: 1 11 16
end; PRINCIPLES OF PROGRAMMING LANGUAGES 28
Advantages to using subprograms

There are several advantages to using subprograms:


They help to keep the code simple and more readable
They allow the programmer to use the same code as many times as
needed throughout the program
They allow the programmer to define needed functions
They can be used in other programs

PRINCIPLES OF PROGRAMMING LANGUAGES 29


Runtime Storage Organization

Stack
Multiple memory uses on computer:
OS memory needs; e.g. ½ for Windows
Program code
User program data
Heap
Function invocations
Temporaries
Static Data
I/O buffers
Code
etc.
Different requirements, caused by differences in: lifetime, Reserved Space

size, access rights. Result: static space, stack, and heap

PRINCIPLES OF PROGRAMMING LANGUAGES HM 30


Runtime Stack

Stack needed for data that are pushed and popped dynamically, following a last-in, first-
out pattern
Space needed at moment of function call, freed at moment of return
Allocation and de-allocation can be implemented cheaply, by adjusting stack pointer;
though “old” data remain in memory
More efficient use of space than static allocation
Most newer imperative languages use stack storage for data associated with activations;
became popular with Algol60

PRINCIPLES OF PROGRAMMING LANGUAGES HM 31


Functions and Activations

Functions, procedures (methods), and classes constitute a form of programming abstraction


focus here functions, not classes
Allow program to be divided into named components with hidden internals
returning a result to place on invocation
Permits code re-use
Each function invocation at runtime is called an activation
Each activation has its own data: formals => actuals, and locals
Storage for these data is called an Activation Record (AR). AKA Stack Frame
Many activations for the same function can exist at one moment of time, due to recursive calls
Data associated with one activation are independent from all others
Normally, an activation record is created when a function is invoked and is destroyed when the function returns

PRINCIPLES OF PROGRAMMING LANGUAGES HM 32


Activation Records: Activation record typically contain the
following entries:

Return address: the address of instruction after the call


Formal parameters: sequence of parameters passed to function by caller
At call: actuals. Inside function: formals. Actuals are bound to formals
Return value: a place for storing the function return value
Local data: storage for local variables
Access link: AKA static link, a pointer to next activation record in chain for accessing non-local data
e.g. lexically enclosing function’s AR, as in Algol, Ada, Pascal, PLI
Control link: AKA dynamic link, pointer to caller’s activation record
Saved machine status: holds info about the machine (i.e. registers’ values) just before the function is called
Temporaries: storage for compiler-allocated temporary objects (e.g. dynamic arrays)

PRINCIPLES OF PROGRAMMING LANGUAGES HM 33


Function Call: When a Method is activated = Function
is Called:

The Caller: The Callee:


saves (some) register values and other
allocates [part of] an activation record for the
machine status info
callee allocates and initializes its local data
evaluates the actual parameters, and stores them and begins execution
into AR Allocates temps, if needed
stores a return address [or return slot] into the AR
if needed, saves (some) register values into the AR
stores current AR pointer (AKA bp for base pointer)
and updates it to point to callee’s AR
But which place in the AR?
transfers control to the callee

PRINCIPLES OF PROGRAMMING LANGUAGES 34


Function Call, Cont’d

Upon Returning
The Callee:
places return value at place the caller can access
restores caller’s AR pointer and other registers, using saved info in stack marker
returns control to the caller
The Caller
can copy the returned value into its own AR
On some architectures: frees space for actuals

PRINCIPLES OF PROGRAMMING LANGUAGES 35


Activation Record for Stack-Dynamic Local Variables

Local variables

Parameters

Dynamic link

Return address

Runtime Stack
PRINCIPLES OF PROGRAMMING LANGUAGES 36
ARI Example for a C Function
Local sum
void sub (float total,
int part) { Local list 4

int list[5]; Local list 3

float sum; Local list 2

… Local list 1

Local list 0
}
Parameter part
Parameter total
Dynamic link
Return address

PRINCIPLES OF PROGRAMMING LANGUAGES 37


C Subprograms (no recursion)

void A(int x) { void C(int q) {


int y; ...
... }
void main() {
C(y);
float p;
... ...
} B(p);
void B(float r) { ...
int s, t; }
...
A(s);
...
}

PRINCIPLES OF PROGRAMMING LANGUAGES 38


Stack after MAIN calls B
main calls B

Top
Local t
Local s
Parameter r
ARI
for B Dynamic link
Static link
Return (to MAIN)
ARI Local p
for MAIN

void main() { void B(float r) {


float p; ... int s, t; ...
B(p);... A(s); ...
} }

PRINCIPLES OF PROGRAMMING LANGUAGES 39


Stack after B calls A
main calls B calls A

Top
Local y
Parameter x
ARI Dynamic link
for A
Static link
Return to B
Top
Local t
Local t
Local s Local s
Parameter r Parameter r
ARI ARI
for B Dynamic link for B Dynamic link
Static link Static link
Return (to MAIN) Return (to MAIN)
ARI Local ARI Local
p p
for MAIN for MAIN

void main() { void B(float r) { void A(int x) {


float p; ... int s, t; ... int y; ...
B(p);... A(s); ... C(y); ...
} } }

PRINCIPLES OF PROGRAMMING LANGUAGES 40


Stack after A calls C
main calls B calls A calls C Top
Parameter q
Dynamic link
ARI
for C Static link
Return to A
Top
Local y Local y
Parameter x Parameter x
ARI Dynamic link ARI Dynamic link
for A for A
Static link Static link
Return to B Return to B
Top
Local t
Local t Local t
Local s Local s Local s
Parameter r Parameter r Parameter r
ARI ARI ARI
for B Dynamic link for B Dynamic link for B Dynamic link
Static link Static link Static link
Return (to MAIN) Return (to MAIN) Return (to MAIN)
ARI Local ARI Local ARI Local
p p p
for MAIN for MAIN for MAIN

void main() { void B(float r) { void A(int x) { void C(int q) {


float p; ... int s, t; ... int y; ... ...
B(p);... A(s); ... C(y); ... }
} } }

PRINCIPLES OF PROGRAMMING LANGUAGES 41


Activation Records in Recursion

int factorial(int n) {
if (n <= 1)
return 1
else
Functional value
return (n * factorial(n-1));
Parameters 3 }

Dynamic link void main() {


int value;
Return address value = factorial(3);

}
Main

PRINCIPLES OF PROGRAMMING LANGUAGES 42


Activation Records for factorial
Return value
int factorial(int n) {
Parameters
2
if (n <= 1)
Dynamic link
return 1;
Return address else
return (n * factorial(n-1));
Return value
}
Parameters 3 void main() {
Dynamic link int value;
value = factorial(3);
Return address
}

Main

PRINCIPLES OF PROGRAMMING LANGUAGES 43


Activation Records for factorial
Return value
Return 1
Parameters 1 int factorial(int n) {
Dynamic link
if (n <= 1)
Return address
return 1;
Return 1 Return value
2*1=2 Parameters else
2
Dynamic link return (n * factorial(n-1));
Return address }
Return value void main() {
Return 1
int value;
3*2=6 Parameters 3
value=factorial(3);
Dynamic link
Return address }

Main 3

PRINCIPLES OF PROGRAMMING LANGUAGES 44


Simple call-return
subprograms
Execution of subprograms

 Subprogram definition: written program ->


template
 Subprogram activation: create an activation using
definition template

PRINCIPLES OF PROGRAMMING LANGUAGES 45


Activation
Each subprogram has a block of storage containing information,
called an Activation record.

Consider the following C subprogram:


float FN( float X, int Y)
const initval=2;
#define finalval 10
float M(10); int N;
N = initval;
if(N<finalval){ ... }
return (20 * X + M(N)); }
Information about procedure FN is contained in its activation record.

PRINCIPLES OF PROGRAMMING LANGUAGES 46


Subprogram activation
a code segment (the invariant part) -
executable code and constants,

an activation record (the dynamic part) –

 local data, parameters


 created anew each time the subprogram
is called
destroyed when the subprogram returns

PRINCIPLES OF PROGRAMMING LANGUAGES 47


System-defined pointers

 Current-instruction pointer – CIP address of the next


statement to be executed

 Current-environment pointer – CEP pointer to the


activation record.

PRINCIPLES OF PROGRAMMING LANGUAGES 48


On call instruction
◦ An activation record is created
◦ Current CIP and CEP are saved in the created activation record
as return point
◦ CEP is assigned the address of the activation record.
◦ CIP gets the address of the first instruction in the code segment
◦ The execution continues from the address in CIP

PRINCIPLES OF PROGRAMMING LANGUAGES 49


On return instruction

◦ The old values of CIP and CEP are retrieved.

◦ The execution continues from the address in CIP

Restrictions of the model:


at most one activation of any subprogram

PRINCIPLES OF PROGRAMMING LANGUAGES 50


Fig. Execution state at start of execution of subprogram B

PRINCIPLES OF PROGRAMMING LANGUAGES 51


Fig. Subprogram call-return structure

PRINCIPLES OF PROGRAMMING LANGUAGES 52


Recursive Subprograms
Specification
Syntactically - no difference
Semantically - multiple activations of same subprogram
exist simultaneously at some point in the execution.

e.g. the first recursive call creates a second activation within the
lifetime of the first activation.

PRINCIPLES OF PROGRAMMING LANGUAGES 53


Recursive Subprograms
Implementation
Stack-based -

• CIP and CEP: stored in stack, dynamic chain of links.


• A new activation record: each call and destroyed on return.
• The lifetimes of the activation records: cannot overlap (nested)

PRINCIPLES OF PROGRAMMING LANGUAGES 54


Implementation
Stack-based -

• CIP and CEP are stored in stack, forming a dynamic


chain of links.

• A new activation record is created for each call and


destroyed on return.

• The lifetimes of the activation records cannot overlap -


they are nested.

PRINCIPLES OF PROGRAMMING LANGUAGES 55


The simplest implementation
• Allocate storage for a single activation record statically as an
extension of the code segment.
• Used in FORTRAN and COBOL.

• The activation record is not destroyed - only reinitialized for each


subprogram execution.

• Hardware support - CIP is the program counter,


• CEP is not used, simple jump executed on return.

PRINCIPLES OF PROGRAMMING LANGUAGES 56


Stack-based implementation
The simplest run-time storage management technique

call statements : push CIP and CEP


return statements : pop CIP and CEP off of the stack.

Used in most C implementations


LISP: uses the stack as an environment.

PRINCIPLES OF PROGRAMMING LANGUAGES 57


Activation record elements

Fig. C memory organisation

PRINCIPLES OF PROGRAMMING LANGUAGES 58


Static and Dynamic Scope
The dynamic scope of an association for an identifier:

• the set of subprogram activations in which the association is visible during


execution.
• tied to the dynamic chain of subprogram activations.

The static scope of a declaration

the part of the program text where the declared identifier is used.

PRINCIPLES OF PROGRAMMING LANGUAGES 59


Dynamic scope rules
Static scope rules

Dynamic scope rules :


Relate references with associations for names during
program execution

Static scope rules :


relate references with declarations of names in the
program text.

PRINCIPLES OF PROGRAMMING LANGUAGES 60


Block structure
Block-structured languages :

 Each program or subprogram is organized as a set of nested


blocks.

 Each block introduces a new local referencing environment.

PRINCIPLES OF PROGRAMMING LANGUAGES 61


Subprogram A

Declaration of X
Declaration of Y

Subprogram B Static scope rules


Declaration of Y for block-
Declaration of Z structured
Use of Y programs

Use of X

Use of Z Hidden to A

PRINCIPLES OF PROGRAMMING LANGUAGES 62


Local Data and Local Referencing
Environments
Local environment of a subprogram:
various identifiers declared in the subprogram :
variables, parameters, subprogram names.

Static scope rules: implemented by means of a table of the local declarations

Dynamic scope rules:


Retention - Associations and the bound values are retained after execution
Deletion - Associations are deleted

PRINCIPLES OF PROGRAMMING LANGUAGES 63


Implementation of dynamic scope rules

By means of a local environment table to associate names, types and


values.

Retention: the table is kept as part of the code segment

Deletion: the table is kept as part of the activation record,


destroyed after each execution.

PRINCIPLES OF PROGRAMMING LANGUAGES 64


Attributes of Data Control
Data control features determine the accessibility of data at
different points during program execution.

Central problem:
the meaning of variable names, i.e. the correspondence between
names and memory locations.

PRINCIPLES OF PROGRAMMING LANGUAGES 65


Names and Referencing Environments

Two ways to make a data object available as an operand for an


operation

Direct transmission
Referencing through a named data object

PRINCIPLES OF PROGRAMMING LANGUAGES 66


Direct transmission
A data object computed at one point as the result of an operation
may be directly transmitted to another operation as an operand

Example: x = y + 2*z;

The result of multiplication is transmitted directly as an operand


of the addition operation

PRINCIPLES OF PROGRAMMING LANGUAGES 67


Referencing through a named data object

A data object may be given a name


when it is created,

the name may then be used to designate it as an operand of


an operation.

PRINCIPLES OF PROGRAMMING LANGUAGES 68


Program elements that may be named
Variables
Formal parameters
Subprograms
resolved at translation time:
Defined types
Defined constants
Labels
Exception names
Primitive operations
Literal constants

PRINCIPLES OF PROGRAMMING LANGUAGES 69


Associations and Referencing
Environments

Association: binding identifiers to particular data objects and


subprograms

Referencing environment: the set of identifier associations for a


given subprogram.

Referencing operations during program execution: determine the


particular data object or subprogram associated with an identifier

PRINCIPLES OF PROGRAMMING LANGUAGES 70


Local referencing environment

The set of associations created on entry to a


subprogram
formal parameters,
local variables, and
subprograms defined only within that subprogram

PRINCIPLES OF PROGRAMMING LANGUAGES 71


Non-local referencing environment
The set of associations for identifiers
• used within a subprogram
• not created on entry to it

Global referencing environment:


associations created at the start of execution of the main program,
available to be used in a subprogram

Predefined referencing environments:


predefined associations in the language definition
PRINCIPLES OF PROGRAMMING LANGUAGES 72
Associations
Visibility of associations

Associations are visible if they are


part of the referencing environment.
Otherwise associations are hidden

Dynamic Scope of associations

The set of subprogram activations within which the


association is visible
PRINCIPLES OF PROGRAMMING LANGUAGES 73
Aliases for Data Objects

Multiple names of a data object


- separate environments - no problem
- in a single referencing environment - called aliases.

Problems with aliasing


• Can make code difficult to understand
• Implementation difficulties at the optimization step -
difficult to spot interdependent statements - not to reorder
them

PRINCIPLES OF PROGRAMMING LANGUAGES 74


Example of aliasing
Program main;
var I: integer;
procedure Sub1 ( var J: integer);
begin
……… (* I and J refer to same data object *)
end;
begin
…. Sub1(I);
….
end.

PRINCIPLES OF PROGRAMMING LANGUAGES 75


Lifetime
The lifetime of a variable is that period during program execution when the storage for
the declared variable exists in some activation record (i.e., from the time the activation
record for the declaring procedure is created until that activation record is destroyed).

The scope of a variable is the portion of the source program where the data item can be
accessed (i.e., the name of the item is a legal reference at that point in the program).

PRINCIPLES OF PROGRAMMING LANGUAGES 76


Lifetimes of variables
Lifetime of variable X is the period when the activation record for P exists.
Note that we can change the scope, but the not lifetime of a variable by nesting
procedures:

PRINCIPLES OF PROGRAMMING LANGUAGES 77


FAQs
Consider the following program. Give the three numbers printed in the cases that Y is
transmitted to P (a) by value (b) by reference, (c) by value-result, and (d) by name.
Program Main(…);
Var Y:interger;
Procedure P(X:integer);
begin X:=X+1; write(X,Y) end;
begin
Y:=1; P(Y); write(Y)
end.

PRINCIPLES OF PROGRAMMING LANGUAGES 78


FAQs
Q1. Explain the Various Design issues that are involved in functions?
Q2. Difference between procedures and functions?
Q3. Mention the various ways for parameter passing & explain each with an example.
Q4. Analyze and discuss the dynamic scope rules and static scope rules.
Q5. What is CIP and CEP?

PRINCIPLES OF PROGRAMMING LANGUAGES 79


References
Book
Terrence W. Pratt, Marvin V. Zelkowitz, “Programming Languages:
Design and Implementation”

PRINCIPLES OF PROGRAMMING LANGUAGES 80

S-ar putea să vă placă și