112
ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

  • View
    218

  • Download
    0

Embed Size (px)

Citation preview

Page 1: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

ISBN 0-321-33025-0

Chapter 7

Expressions and Assignment Statements

CE2004 Principles of

Programming Languages

EIGHTH EDITION

Page 2: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-2

Evaluation of Variables and Constants

• Variables in expressions are evaluated by fetching their values from memory.

• Constants are sometimes evaluated the same way.

• In other cases, a constant may be part of the machine language instruction and not require a memory fetch.

Page 3: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-3

Evaluation of Parenthesized Expression

• If an operand is a parenthesized expression, then all operators it contains must be evaluated before its value can be used as an operand.

Page 4: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-4

Side Effects and Evaluation Order

• If neither of the operands of an operator has side effect, then operand evaluation order is irrelevant.

Page 5: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-5

Side Effects

• A side effect of a function, called a functional side effect, occurs when the function changes one of its– parameters or – a global variables.

• A global variable is declared outside the function but is accessible in the function.

Page 6: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-6

Example – without Side Effects

• Consider the expression

a + fun (a)

• If fun does not have the side effect of changing a, then the order of evaluation of the two operand, a and fun(a), has no effect on the value of the expression.

Page 7: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-7

Example – with Side Effects

a + fun (a)

• If fun changes a, there is an effect.

Page 8: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-8

Assumption

• Consider the following situation: – fun returns 10 and changes the value of its

parameter to 20.– Suppose we have the following statements:

a = 10;

b = a + fun(a);

Page 9: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-9

Different Evaluation Orders Create Different Results

• If the value of a is fetched first (in the expression evaluation process), its value is 10 and the value of the expression is 20.

• If the second operand is evaluated first, then the value of the first operand is 20 and the value of the expression is 30.

Page 10: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-10

Example

int a = 5;int fun1() { a = 17 ; return 3;} /* end of fun1 */

void main() { a = a + fun1();} /* end of main */

• The value computed for a in main depends on the order of evaluation of the operands in the expression a + fun1().

• The value of a will be – either 8 (if a is evaluated first) or – 20 (if the function call is evaluated first).

Page 11: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-11

Multiple Use of Notations

• Arithmetic operators are often used for more than one purpose.– For example, in the imperative programming

languages + is used to specify • integer addition and • floating-point addition. • Some languages, java, for example, also use it for

string catenation.

Page 12: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-12

Operator Overloading

• The multiple use of an operator is called operator overloading.

• Operator overloading is generally thought to be acceptable, as long as readability and/or reliability do not suffer.

Page 13: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-13

Ampersand (&) in C

• As a binary operator, it specifies a bitwise logical AND operation.

• As a unary operator with a variable as its operand, the expression value is the address of that variable.– In this case, the ampersand is called the

address-of operator.

Page 14: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-14

Possible Dangers of Overloading

• There are two problems with the multiple use of the ampersand.– First, using the same symbol for two

completely unrelated operations is detrimental to readability.

– Second, the simple keying error of leaving out the first operand for a bitwise AND operation can go undetected by the compiler, because it is interpreted as an address-of operator.

• Such an error may be difficult to diagnose.

Page 15: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-15

Short-Circuit Evaluation

Page 16: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-16

Short-Circuit Evaluation

• A short-circuit evaluation of an expression is one in which the result is determined without evaluating all of the operands and/or operators.

Page 17: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-17

Example

• For example, – the value of the arithmetic expression (3 * a) * (b / 13 - 1) is independent of the value of (b / 13 - l) if a is 0, because 0 * x = 0 for any x.

– So when a is 0, there is no need to evaluate• (b / 13 - l) or • perform the second multiplication.

• However, in arithmetic expressions this shortcut is not easily detected during execution, so it is NEVER taken.

Page 18: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-18

Another Example

• The value of the Boolean expression (a >= 0) && (b < 10) is independent of the second relational expression if a < 0, because (FALSE && x) is FALSE for all values of x.

• So when a < 0, there is no need to evaluate b, the constant 10, the second relational expression, or the && operation.

• Unlike the case of arithmetic expressions, this shortcut can be easily discovered during execution and taken.

Page 19: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-19

A Potential Problem with Non-short-Circuit Evaluation of Boolean Expressions

• Suppose – suppose we write a table lookup loop using the while

statement. – assuming

• list, which has listlen elements, is the array to be searched• key is the searched-for value

index = 0; while ((index < listlen) && (list[index] <> key)) index = index +1 ;

• If evaluation is not short circuit, both relational expressions in the Boolean expression of the while statement are evaluated, regardless of the value of the first.

• Thus, if key is not in list, The iteration that has index == listlen will reference list[listlen], which causes the indexing error because list is declared to have listlen-l as an upper bound subscript value.

Page 20: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-20

Short-circuit Evaluation Could Solve the Previous Problem

• If a language provides short-circuit valuation of Boolean expressions and it is used, situation in the previous slide is not a problem.

• In the preceding example, a short-circuit evaluation scheme would evaluate the first operand of the AND operator, but it would skip the second operand if the first operand is false.

Page 21: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-21

Short-Circuit Evaluation May Result in Errors

• Short-circuit evaluation of expressions exposes the problem of allowing side effects in expressions.

• Suppose that – short-circuit evaluation is used on an expression and – part of the expression that contains a side effect is not

evaluated

then the side effect will only occur in complete evaluations of the whole expression. • If program correctness depends on the side

effect, short-circuit evaluation can result in a serious error.

Page 22: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-22

Example

• Considconsider the C expression (a > b) || (b++ / 3)

• In this expression, b is changed (in the second arithmetic expression) only when a<=b.

• If the programmer assumed b would be changed every time this expression is evaluated during execution, the program will fail.

Page 23: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

ISBN 0-321-33025-0

Chapter 9

Subprograms

CE2004 Principles of

Programming Languages

EIGHTH EDITION

Page 24: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-24

Chapter 9 Topics

• Introduction• Fundamentals of Subprograms• Design Issues for Subprograms• Local Referencing Environments• Parameter-Passing Methods• Parameters That Are Subprogram Names• Overloaded Subprograms• Generic Subprograms• Design Issues for Functions• User-Defined Overloaded Operators• Coroutines

Page 25: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-25

Abstraction Facilities in a Programming Language

• Two fundamental abstraction facilities can be included in a programming language: – process abstraction

• In the early history of high-level programming languages, only process abstraction was recognized and included.

• Process abstraction has been a central concept in all programming languages.

– data abstraction• In the 1980s, however, many people began to

believe that data abstraction was equally important. • Data abstraction is discussed in detail in Chapter 11.

Page 26: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-26

Properties of Subprograms

• All subprograms discussed in this chapter, except the coroutines described in Section 9.11, have the following characteristics; – Each subprogram has a single entry point. – The calling program unit is suspended during the

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

– Control always returns to the caller when the subprogram execution terminates.

Page 27: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-27

Subprogram Definitions

• A subprogram definition describes the interface to and the actions of the subprogram abstraction.

Page 28: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-28

Subprogram Call

• A subprogram call is the explicit request that the called subprogram be executed.

Page 29: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-29

Active Subprogram

• A subprogram is said to be active if, after having been called, it has begun execution but has not yet completed that execution.

Page 30: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-30

Classes of Subprograms

• The two fundamental kinds of subprograms,– procedures and – functions,

are defined and discussed in Section 9.2.4.

Page 31: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-31

Subprogram Headers

• A subprogram header, which is the first part of the definition, serves several purposes. – First, it specifies that the following syntactic unit

is a subprogram definition of some particular kind.

• Some programming languages include two different kinds of subprograms; specifically, procedures and functions.

– Second, it provides a name for the subprogram.– Third, it may optionally specify a list of

parameters. • They are optional because not all subprogram

definitions have parameters.

Page 32: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-32

Header Examples

• The following is the header of a Fortran subprogram named Adder.

Subroutine Adder(parameters)

• In Ada, the header for Adder would be

procedure Adder(parameters)

Page 33: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-33

C Function Header

• No special word appears in the subprogram header of a C subprogram.

• C has only one kind of subprogram, functions (and/or methods).

• The header of a function is recognized by context rather than by a special word.

• For example,

void adder(parameters)

– would serve as the header of a function named adder, where void indicates that it does not return a value.

Page 34: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-34

The Parameter Profile and the Protocol of a Subprogram

• The parameter profile (sometimes called the signature) of a subprogram is the – number– order and – types

of its formal parameters.

• The protocol of a subprogram is its parameter profile plus, if it is a function, its return type.

Page 35: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-35

The Declarations of Variables in C

• In C the declarations of variables can be used to provide type information but not to define variables.

• A variable declaration in C is used only outside function definitions.

• A declaration is necessary when a variable must be referenced before the compiler has seen its definition.

Page 36: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-36

Subprogram Declarations

• Subprograms can have declarations as well as definitions. – This form parallels the variable declarations

and definitions in C.

• Subprogram declarations provide the subprogram’s protocol, but do not include their bodies. – They are necessary in languages that do not

allow forward references to subprograms.

Page 37: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-37

Declaration and Type Checking

• In both the cases of variables and subprograms, declarations are needed for static type checking. – In the case of subprograms, it is the type of

the parameters that must be checked.

Page 38: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-38

Usage of Subprogram Declarations

• Function declarations are common in C and C++ programs, where they are called prototypes.

• In most other languages, subprograms do not need declarations, because there is no requirement that subprograms defined before they are called.

Page 39: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-39

Approaches a Subprogram Could Use to Access Data

• Subprograms typically describe computations.

• There are two ways that a non-method subprogram can gain access to the data that it is to process: – through direct access to nonlocal variables

(declared elsewhere but visible in the subprogram)

– through parameter passing.

Page 40: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-40

Data Passing through Parameters

• Data passed through parameters are accessed through names that are local to the subprogram.

• Parameter passing is more flexible than direct access to nonlocal variables.

Page 41: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-41

Parameterized Computation

• In essence, a subprogram with parameter access to the data that it is to process is a parameterized computation. – It can perform its computation on whatever

data it receives through its parameters (presuming the types of the parameters are as expected by the subprogram).

Page 42: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-42

Disadvantages of Data Access through Non-local Variables

• If data access of a subprogram is through nonlocal variables, the only way the computation can proceed on different data is to assign new value to those nonlocal variables between calls to the subprogram.

• Variables that are visible to the subprogram where access is desired often end up also being visible where access to them is not needed (see chapter 5).

Page 43: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-43

Using a Subprogram as a Parameter• In some situations, it is convenient to be

able to transmit computations, rather than data, as parameters to subprograms.

• In these cases, the name of the subprogram that implements that computation may be used as a parameter.

Page 44: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-44

Formal Parameters

• The parameters in the subprogram header are called formal parameters.

• They are sometimes thought of as dummy variables because they are not variables in the usual sense: In some cases, they are bound to storage only when the subprogram is called.

Page 45: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-45

Actual Parameters

• Subprogram call statements must include– the name of the subprogram– a list of parameters to be bound to the formal

parameters of the subprogram. • These parameters are called actual parameters. • They must be distinguished from formal

parameters because the two can have different restrictions on their forms, and of course their uses are quite different.

Page 46: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-46

Positional Parameters

• In nearly all programming languages, the correspondence between actual and formal parameters—or the binding of actual parameters to formal parameters—is done by simple position: – The first actual parameter is bound to the first

formal parameter and so forth. – Such parameters are called positional parameters.

• This is an effective and safe method for relatively short parameter lists.

Page 47: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-47

Keyword Parameters

• When lists are long, however, it is easy for the programmer to make mistakes in the order of actual parameters in the list.

• One solution to this problem is to provide keyword parameters, in which the name of the formal parameter to which an actual parameter is to be bound is specified with the actual parameter.

Page 48: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-48

Advantages of Keyword Parameters• The advantage of keyword parameters is that

they can appear in any order in the actual parameter list.

• Ada procedures can be called using this method, as in

Sumer(Length => My_Length,

List => My_Array,

Sum => My_Sum);

– where the definition of Sumer has the formal parameters Length, List, and Sum.

Page 49: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-49

Disadvantages of Keyword Parameters

• The disadvantage to keyword parameters is that the user of the subprogram must know the names of formal parameters.

Page 50: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-50

Combining Keyword Parameters with Positional Parameters

• In addition to keyword parameters, Ada and Fortran 90 allow positional parameters.

• The two can be mixed in a call, as in Sumer(Length, List => My_Array, Sum => My_Sum);

• The only restriction with this is that after a keyword parameter appears in the list, all remaining parameters must be keyworded. This is necessary because position may no longer be well defined after a keyword parameter has appeared.

Page 51: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-51

When the Number of Actual Parameters Is Fewer than the Number of Formal Parameters

• In most languages that do not have default values for formal parameters, – the number of actual parameters in a call must match – the number of formal parameters in the subprogram

definition header.

Page 52: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-52

When the Number of Actual Parameters Is Fewer than the Number of Formal Parameters

• However, in C, C++, Perl, and JavaScript the equal-number feature is not required.– When there are fewer actual parameters in a call

than formal parameters in a function definition, it is the programmer's responsibility to ensure that the parameter correspondence, which is always positional, and the subprogram execution are sensible.

Page 53: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-53

Advantages of Variable Number of Parameters

• Although this design, which allows a variable number of parameters, is clearly prone to error, it is also sometimes convenient. – For example, the printf function of C can

print any number of items (data values and/or literal strings).

Page 54: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-54

Disadvantages of Variable Number of Parameters – (1)

• Format string attacks.• E.g. foo() {

int i,j,k;

printf(“%d %d”,i);

}

don’t match

return address of foo()

caller ebp

local variable

:

local variable

parameters

return address of printf()

caller ebp

local variables

Page 55: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-55

Disadvantages of Variable Number of Parameters – (2)

• Format string attacks.• E.g. foo() {

char StingInput[100];

gets(StingInput);printf(StingInput,i);

}

return address of foo()

caller ebp

local variable

:

local variable

parameters

return address of printf()

caller ebp

local variables

Input: “%d %d %d %d\n”

Page 56: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-56

Procedures and Functions

• There are two distinct categories of subprograms: – procedures and – functions,

both of which can be viewed as approaches to extending the language.

Page 57: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-57

Procedures and Subroutines

• Procedures are collections of statements that define parameterized computations.

• These computations are enacted by single call statements.

• In effect, procedures define new statements.– For example, because Ada does not have a sort

statement, a user can build a procedure to sort arrays of data and use a call to that procedure in place of the unavailable sort statement.

• In Ada, procedure are called just that; in Fortran, they are called subroutines.

Page 58: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-58

Send back Results to the Calling Procedures

• Procedures can produce results in the calling program unit by two methods. – First, if there are variables that are not formal

parameters but are still visible in both the procedure and the calling program unit, the procedure can change them.

– Second, if the subprogram has formal parameters that allow the transfer of data to the caller, those parameters can be changed.

Page 59: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-59

Functions

• Functions structurally resemble procedures but are semantically modeled on mathematical functions.

• If a function is a faithful model, it produces no side effects; that is, it modifies neither its parameters nor any variables defined outside the function.

• Such a function returns a value – that is its only desired effect.

• In practice, many functions in programs have side effects.

Page 60: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-60

Function Invoking and Its Return Value

• Functions are called by appearances of their names in expressions, along with the required actual parameters.

• The value produced by a function's execution is returned to the calling code, effectively replacing the call itself. – For example, the value of the expression f(x)

is whatever value f produces when called with the parameter x.

– For a function that does not produce side effects, the returned value is its only effect.

Page 61: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-61

Functions Define New User-defined Operators

• For example, if a language does not have an exponentiation operator, a function can be written that returns the value of one of its parameters raised to the power of another parameter.

• Its header in C++ could be

float power (float base, float exp)

which could be called with

result = 3.4 * power(10.0, x)

Page 62: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-62

Overloaded Subprograms and Generic Subprograms

• An overloaded subprogram is one that has the same name as another subprogram in the same referencing environment.

• A generic subprogram is one whose computation can be done on data of different types in different calls.

Page 63: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-63

Semantics Models of Formal Parameters

• Formal parameters are characterized by one of three distinct semantics models: 1. they can receive data from the corresponding

actual parameter; 2. they can transmit data to the actual

parameter; 3. they can do both.

• These three semantics models are called– in mode

– out mode

– inout mode

Page 64: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-64

Figure 9.1

Page 65: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-65

Conceptual Models of How Data Transfers Take Place

• There are two conceptual models of how data transfers take place in parameter transmission;– either an actual value is copied (to the caller, to

the callee, or both ways)– an access path is transmitted

• Most commonly, the access path is a simple pointer or reference.

Page 66: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-66

Implementation Models of Parameter Passing

• Pass-by-Value• Pass-by-Result• Pass-by-Value-Result• Pass-by-Reference• Pass-by-Name

Page 67: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-67

Pass-by-Value

• When a parameter is passed by value, the value of the actual parameter is used to initialize the corresponding formal parameter, which then acts as a local variable in the subprogram, thus implementing in-mode semantics.

Page 68: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-68

Approaches to Implement Pass-by-Value• Pass-by-value is normally implemented by copy,

because accesses are usually more efficient with this method.

• It could be implemented by transmitting an access path to the value of the actual parameter in the caller, but that would require that the value be in a write-protected cell (one that can only be read).– Enforcing the write protection is not always a simple

matter. • For example, suppose the subprogram to which the

parameter was passed passes it in turn to another subprogram.

Page 69: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-69

Advantages of the Pass-by-Value Method

• For Scalars it is fast, in access time.

Page 70: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-70

Disadvantages of the Pass-by-Value Method

• The main disadvantage of the pass-by-value method if copies are used is that additional storage is required for the formal parameter, either– in the called subprogram – in some area outside both the caller and the called

subprogram

• In addition, the actual parameter must be copied to the storage area for the corresponding formal parameter.

• The storage and the copy operations can be costly if the parameter is large, such as an array with many elements.

Page 71: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-71

Pass-by-Result

• Pass-by-result is an implementation model for out-mode parameters.

• When a parameter is passed by result, NO value is transmitted to the subprogram.

• The corresponding formal parameter acts as a local variable, but just before control is transferred back to the caller, its value is transmitted back to the caller's actual parameter, which obviously must be a variable,

Page 72: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-72

Price to Pay for Different Implementations

• If values are returned by copy (as opposed to access paths), as they typically are, pass-by-result also requires the extra storage and the copy operations that are required by pass-by-value.

• As with pass-by-value, the difficulty of implementing pass-by-result by transmitting an access path usually results in it being implemented by data copy. – In this case, the problem is in ensuring that the initial

value of the actual parameter is not used in the called subprogram.

Page 73: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-73

Problem

• One problem with the pass-by-result model is that there can be an actual parameter collision, as shown in the next slide.

Page 74: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-74

Actual Parameter Collision Problem• call sub(p1,p1)

– In sub, assuming the two formal parameters have different names, the two can obviously be assigned different values.

– Then whichever of the two is assigned to their corresponding actual parameter last becomes the value of p1. Thus the order in which the actual parameters are assigned determines their value.

– Because the order is sometimes implementation-dependent, for some languages, different implementations can produce different results.

Page 75: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-75

Example – a C# Method

void Fixer(out int x, out int y){ x = 17; y = 35;}...f.Fixer(out a, out a);

• If at the end of the execution of Fixer the formal parameter x is assigned to its corresponding actual parameter first, the value of the actual parameter a in the caller will be 35

• If y is assigned first, the value of a in the caller will be 17.

Page 76: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-76

Another Problem of Pass-by-Result

• The implementor may be able to choose between two different times to evaluate the addresses of the actual parameters; – at the time of the call

or– at the time of the return.

Page 77: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-77

Example – a C# Method (1)

void DoIt(out int x, out int index)

{

x = 17 ;

index = 42;

}

...

sub = 21;

f.DoIt(list[sub], sub);

Page 78: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-78

Example – a C# Method (2)

• The address of list[sub] changes between the beginning and end of the method.

• The implementor must choose the time at which the address to which to return the value will be determined, – at the time of the call or– at the time of the return.

Page 79: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-79

Example – a C# Method (3)

• If the address is computed on entry to the method, the value 17 will be returned to list[21].

• If computed just before return, 17 will be returned to list[42].

• This makes programs unportable between– an implementation that chooses to evaluate

the addresses for out-mode parameters at the beginning of a subprogram

and– one that choose to do that evaluation at the

end.

Page 80: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-80

Pass-by-Value-Result

• Pass-by-value-result is an implementation model for inout-mode parameters in which actual values are copied.

• It is in effect a combination of pass-by-value and pass-by-result. – The value of the actual parameter is used to initialize the

corresponding formal parameter, which then acts as a local variable.

• In fact, pass-by-value-result formal parameters must have local storage associated with the called subprogram.

– At subprogram termination, the value of the formal parameter is transmitted back to the actual parameter.

Page 81: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-81

Alias of Pass-by-Value-Result

• Pass-by-value-result is sometimes called pass-by-copy because the actual parameter is copied to the formal parameter at subprogram entry and then copied back at subprogram termination.

Page 82: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-82

Disadvantages and Problems of Pass-by-Value-Result

• Pass-by-value-result shares with pass-by-value and pass-by-result the disadvantages of – requiring multiple storage for parameters and– time for copying values.

• It shares with pass-by-result the problems associated with the order in which actual parameters are assigned.

Page 83: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-83

Pass-by-Reference

• Pass-by-reference is a second implementation model for inout-mode parameters.

• Rather than copying data values back and forth, however, the pass-by-reference method transmits an access path, usually just an address, to the called subprogram.

• This provides the access path to the cell storing the actual parameter. Thus the called subprogram is allowed to access the actual parameter in the calling program unit.

• In effect, the actual parameter is shared with the called subprogram.

Page 84: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-84

Advantages

• The advantage of pass-by-reference is that the passing process itself is efficient, in terms of both time and space.

• Duplicate space is not required, nor is any copying required.

Page 85: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-85

Disadvantages – Indirect Addressing and Unnecessary Access

• There are, however, several disadvantages to the pass-by-reference method. – First, access to the formal parameters will be

slower than pass-by-value parameters, because of the additional level of indirect addressing that is required.

– Second, if only one-way communication to the called subprogram is required, inadvertent and erroneous changes may be made to the actual parameter.

Page 86: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-86

Disadvantages – Alias (1)

• Another serious problem of pass-by-reference is that aliases can be created.

• This should be expected because pass-by-reference makes access paths available to the called subprograms, thereby broadening their access to nonlocal variables.

Page 87: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-87

Disadvantages – Alias (2)

• The problem with these kinds of aliasing is the same as in other circumstance:– It is harmful to readability and thus to

reliability.– It also makes program verification extremely

difficult.

Page 88: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-88

Aliases – (1)

• When parameters are passed by reference, collisions can occur between actual parameters.

• Consider a C function procedure that has two parameters that are to be passed by reference, as in

void fun(int *first, int *second)

• If the call to fun happens to pass the same variable twice, as in

fun(&total, &total)

then first and second in fun will be aliases.

Page 89: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-89

Aliases – (2)

• Collisions between array elements can also cause aliases.

• For example:– Suppose the function fun is called with two

array elements that are specified with variable subscripts, as in fun(&list[i], &list[j]).

– If i is equal to j, then first and second are again aliases.

Page 90: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-90

Aliases – (3)

• Collisions between call-by-reference formal parameters and nonlocal variables that are visible.

• For example, consider the following C code:

int *global;void main(){ ... sub(global); ...}void sub(int *param){ ...}

– Inside sub, param and global are alias.

Page 91: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-91

Pass-by-Name

• Pass-by-name is an inout-mode parameter transmission method that does not correspond to a single implementation model.

• When parameters are passed by name, the actual parameter is, in effect, textually substituted for the corresponding formal parameter in all its occurrences in the subprogram.

Page 92: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-92

Differences between Pass-by-Name and Other Approaches

• Pass-by-name is quite different from the methods discussed thus far.– In those cases, formal parameters are bound

to actual values or addresses at the time of the subprogram call.

– A pass-by-name formal parameter is bound to an access method at the time of the subprogram call, but the actual binding to a value or an address is delayed until the formal parameter is assigned or referenced.

Page 93: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-93

Example - Algol

procedure double(x); real x; begin x := x * 2 end;

• In general, the effect of pass-by-name is to textually substitute the argument expressions in a procedure call for the corresponding parameters in the body of the procedure, e.g., double(C[j]) is interpreted as C[j] := C[j] * 2.

• Technically, if any of the variables in the called procedure clash with the caller's variables, they must be renamed uniquely before substitution

Page 94: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-94

Pass-By-Name Security Problem

procedure swap (a, b);

integer a, b, temp;

begin

temp := a;

a := b;

b:= temp

end;

• Effect of the call swap(i, x[i]): temp := i;

i := x[i];

x[i] := temp

It doesn't work! For example:

Page 95: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-95

Resulting Semantics

• If an actual parameter is a scalar variable, it is pass-by-reference.

• If an actual parameter is a constant expression, it is pass-by-value.

Page 96: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-96

Run-Time Stacks and Parameter Passing

• In most contemporary languages, parameter communication takes place through the run-time stack.

• The run-time stack is used extensively for subprogram control linkage (e.g. return address and caller ebp) and parameter passing, as discussed in Chapter 10.

Page 97: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-97

Assumption

• In the following discussion, the author assumes that the stack is used for all parameter transmission.

Page 98: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-98

Handling Pass-by-Value Parameters

• Pass-by-value parameters have their values copied into stack locations.

• The stack locations then serve as storage for the corresponding formal parameters.

• C uses pass-by-value– In C Pass-by-reference (inout mode) semantics is

achieved by using pointers as parameters.

Page 99: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-99

Handling Pass-by-Result Parameters

• Pass-by-result parameters are implemented as the opposite of pass-by-value.

• The values assigned to the pass-by-result actual parameters are placed in the stack, where they can be retrieved by the calling program unit upon termination of the called subprogram.

Page 100: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-100

Handling Pass-by-Value-Result Parameters

• Pass-by-value-result parameters can be implemented directly from their semantics as a combination of pass-by-value and pass-by-result.

• The stack location for the parameters is initialized by the call and is then used like a local variable in the called subprogram.

Page 101: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-101

Handling Pass-by-Reference Parameters

• Pass-by-reference parameters are perhaps the simplest to implement.

• Regardless of the type of the actual parameter, only its address must be placed in the stack.

Page 102: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-102

Figure 9.2

• sub is called from main with the call sub(w, x, y, z) ,– w is passed by value– x is passed by result– y is passed by value-result– z is passed by reference

• Function header void sub (int a, int b, int c, int d)

Page 103: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-103

Chapter 10

Page 104: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-104

Subprogram Linkage

• The subprogram call and return operations of a language are together called its subprogram linkage.

Page 105: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-105

Activation Record

• The format, or layout, of the noncode part of a subprogram is called an activation record, because the data it describes are only relevant during the activation of the subprogram.

• The form of an activation record is static. • An activation record instance is a concrete

example of an activation record, a collection of data in the form of an activation record.

Page 106: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-106

Return Addresses

• The return address often consists of – a pointer to the code segment of the caller and– an offset address in that code segment of the

instruction following the call.

Page 107: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-107

Dynamic Link

• The dynamic link is a pointer to the top or base point of the activation record instance of the caller.

• In static-scoped languages, this link is used in the destruction of the current activation record instance when the procedure completes its execution.

Page 108: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-108

Figure 10.3

• The above figure is described in the text book. However, the layout of the activation record of a real implementation may be different than it (see next slide for more details).

Page 109: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-109

Layout of an Activation Record of a Real Implementation

Parameters

Return address

Dynamic link

Local variables

Page 110: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-110

A Skeletal C Program

void fun1(int x){ int y; . . . <----------------------------------2 fun3(y); . . .}void fun2(float r){ int s,t; . . . <----------------------------------1 fun1(s); . . .}void fun3(int q){ . . . <----------------------------------3}void main(){ float p; . . . fun2(p); . . .}

Page 111: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-111

The Sequence of Procedure Calls

• The sequence of procedure calls in the program in the previous slide is

main calls fun2fun2 calls fun1fun1 calls fun3

Page 112: ISBN 0-321-33025-0 Chapter 7 Expressions and Assignment Statements CE2004 Principles of Programming Languages EIGHTH EDITION

1-112

Figure 10.5