1 cs 201 computer systems programming chapter 18 “parameter passing” herbert g. mayer, psu cs...

27
1 CS 201 Computer Systems Programming Chapter 18 “Parameter Passing” Herbert G. Mayer, PSU CS Herbert G. Mayer, PSU CS Status 1/23/2913 Status 1/23/2913

Upload: franklin-golden

Post on 14-Jan-2016

214 views

Category:

Documents


0 download

TRANSCRIPT

1

CS 201Computer Systems Programming

Chapter 18“Parameter Passing”

Herbert G. Mayer, PSU CSHerbert G. Mayer, PSU CSStatus 1/23/2913Status 1/23/2913

2

Syllabus

SummarySummary

AliasingAliasing

Parameter OverviewParameter Overview

Value ParameterValue Parameter

Reference ParameterReference Parameter

Value-Result ParameterValue-Result Parameter

Name ParameterName Parameter

In-Out ParameterIn-Out Parameter

ReferencesReferences

3

Summary Passing parameters is Passing parameters is thethe key programming key programming

language tool to language tool to bind caller to calléebind caller to callée

The parameter on the calling side is the actual The parameter on the calling side is the actual parameter (AP); the actual may be an expression or parameter (AP); the actual may be an expression or a named object (variable) depending on parametera named object (variable) depending on parameter

The parameter on the called side (callée) is the The parameter on the called side (callée) is the formal parameter (FP); it is always namedformal parameter (FP); it is always named

The actual is bound to the formal at place of callThe actual is bound to the formal at place of call

Binding lasts for the duration of the callBinding lasts for the duration of the call

Association actual-to-formal is generally by positionAssociation actual-to-formal is generally by position

Association may also be by naming the formal at the Association may also be by naming the formal at the place of call, e.g. in Ada. In that case the order may place of call, e.g. in Ada. In that case the order may be arbitrarily intermixed at the place of callbe arbitrarily intermixed at the place of call

4

Summary Types and numbers of actual and formal parameter (Types and numbers of actual and formal parameter (FPFP) )

generally must be compatible, subject to type generally must be compatible, subject to type compatibility- or type conversion rulescompatibility- or type conversion rules

C/C++ allow a lesser number of actual parameters (C/C++ allow a lesser number of actual parameters (APAP) to ) to be passed than formally declaredbe passed than formally declared

Typical implementation of C/C++ therefore pass actuals in Typical implementation of C/C++ therefore pass actuals in reverse textual order; see detail in Compiler class CA reverse textual order; see detail in Compiler class CA 321/322 or similar321/322 or similar

TheoreticallyTheoretically, APs are passed on the run-time stack, APs are passed on the run-time stack PhysicallyPhysically, good optimizers pass APs in registers, good optimizers pass APs in registers PracticallyPractically, compiler passes the first few parameters in , compiler passes the first few parameters in

registers and remaining ones on the stackregisters and remaining ones on the stack FPs are generally located on one side off the stack FPs are generally located on one side off the stack

marker, while locals are positioned on the opposite side marker, while locals are positioned on the opposite side of the stack marker, one kind requiring negative, the other of the stack marker, one kind requiring negative, the other positive offsets from a base pointer register positive offsets from a base pointer register

5

Summary Value Parameter Value Parameter (VP): Actual parameter (AP) (VP): Actual parameter (AP)

provides initial value via a type-compatible provides initial value via a type-compatible expression. If modifications to bound formal expression. If modifications to bound formal parameter (FP) occur, they do not impact the APparameter (FP) occur, they do not impact the AP

Reference ParameterReference Parameter (RP): AP must be an (RP): AP must be an addressable object. If modifications to bound FP addressable object. If modifications to bound FP occur, they immediately impact the AP. Implemented occur, they immediately impact the AP. Implemented by passing the address of the AP, which is a by passing the address of the AP, which is a variable variable

Value-Result Parameter Value-Result Parameter (VRP): AP must be an (VRP): AP must be an addressable object. If modifications to bound FP addressable object. If modifications to bound FP occur, they do impact the AP, but such assignments occur, they do impact the AP, but such assignments to AP occur at the place of return. Implemented via to AP occur at the place of return. Implemented via copy-in copy-outcopy-in copy-out

Detail and other kinds of formal parameters belowDetail and other kinds of formal parameters below

6

Aliasing Making one machine address accessible via two or Making one machine address accessible via two or

more symbolic names (variables) is known as more symbolic names (variables) is known as aliasingaliasing

We say: object We say: object o2o2 is an alias of object is an alias of object o1o1, if they , if they designate the same memory addressdesignate the same memory address

Alias relation is reflexive: if Alias relation is reflexive: if o1o1 is alias of is alias of o2o2, then , then o2o2 is also an alias of is also an alias of o1o1

When When o1o1 and and o2o2 are aliases, and are aliases, and o1o1 is changed, then is changed, then magically magically o2o2 also changes. Unless the programmer is also changes. Unless the programmer is aware of the alias relation, this magic is a aware of the alias relation, this magic is a surprisesurprise

Aliasing is not always a sign of poor programmingAliasing is not always a sign of poor programming Software using aliasing is generally harder to Software using aliasing is generally harder to

comprehend, thus tends to be more error pronecomprehend, thus tends to be more error prone

7

Aliasing Alias relations are typically established via reference Alias relations are typically established via reference

parametersparameters We can argue whether pointers cause aliasing as We can argue whether pointers cause aliasing as

well; they surely allow programmers to access well; they surely allow programmers to access objects differently than via their nameobjects differently than via their name

Example of aliasing:Example of aliasing:

int glob_i = 109;int glob_i = 109;. . .. . .void foo1( int & loc_i )void foo1( int & loc_i ){ // foo1{ // foo1 ASSERT( 109 == glob_i, "wrong value for glob_i" );ASSERT( 109 == glob_i, "wrong value for glob_i" ); ASSERT( 109 == loc_i, "wrong parameter passing" );ASSERT( 109 == loc_i, "wrong parameter passing" ); loc_i ++;loc_i ++; // what will be changed? // what will be changed? ASSERT( 110 == glob_i, "aliasing failed." );ASSERT( 110 == glob_i, "aliasing failed." );} //end foo1} //end foo1. . .. . .int main( void )int main( void ){ // main{ // main foo1( glob_i );foo1( glob_i ); // the only call to foo1() // the only call to foo1()} //end main} //end main

8

Aliasing Pointers add another aliasing methodPointers add another aliasing method Yet each time we change an object pointed to, we Yet each time we change an object pointed to, we

know: know: this may change memory anywherethis may change memory anywhere Notice Notice Golden Rule Golden Rule violationviolation below! below!

int glob_i = 110;int glob_i = 110;. . .. . .void foo2( void )void foo2( void ){ // foo2{ // foo2 int * p_i = & glob_i;int * p_i = & glob_i; // set local pointer to glob_i // set local pointer to glob_i

ASSERT( 110 == glob_i, "error, glob_i unexpected" );ASSERT( 110 == glob_i, "error, glob_i unexpected" ); ASSERT( 110 == *p_i, "error, * to wrong 1 object" );ASSERT( 110 == *p_i, "error, * to wrong 1 object" ); (*p_i)++; // *p_i is alias of glob_i(*p_i)++; // *p_i is alias of glob_i ASSERT( 111 == glob_i, "error in * assignment" );ASSERT( 111 == glob_i, "error in * assignment" ); ASSERT( 111 == *p_i, "error, * to wrong 2 object" );ASSERT( 111 == *p_i, "error, * to wrong 2 object" ); ++(*p_i); // another way to change++(*p_i); // another way to change ASSERT( 112 == glob_i, "error in pre-inc. via *" );ASSERT( 112 == glob_i, "error in pre-inc. via *" ); *p_i++; // *p_i++; // this fails the ASSERTthis fails the ASSERT ASSERT( 113 == glob_i, "know your precedences" );ASSERT( 113 == glob_i, "know your precedences" );} //end foo2} //end foo2

9

Parameter Overview

10

Value Parameter (VP) The actual parameter (AP) to be bound to a formal The actual parameter (AP) to be bound to a formal

value parameter (VP) must provide an initial value to value parameter (VP) must provide an initial value to the formal parameter (FP)the formal parameter (FP)

Initial value is the first value of the FP; that initial Initial value is the first value of the FP; that initial actual value may be an expression or objectactual value may be an expression or object

During the call, assignments to the formal VP are During the call, assignments to the formal VP are allowed; allowed; exception: in-parameters exception: in-parameters in Adain Ada

Assignments to the formal VP have no impact on AP Assignments to the formal VP have no impact on AP during or after the callduring or after the call

Implementation: must make a copy of the initial Implementation: must make a copy of the initial value of the AP and pass it in register, or more value of the AP and pass it in register, or more generally on the stackgenerally on the stack

At place of return, discard the copy, which At place of return, discard the copy, which immediately voids changes to the FP during the callimmediately voids changes to the FP during the call

11

Value Parameter in C C requires parameter passing C requires parameter passing by valueby value Except for parameters of type array[]Except for parameters of type array[]

Arrays in C and C++ are passed by reference; generally implemented by passing the address of the actual array; in C and C++ that is also element [0]

Not to be confused or equated with pointer types! More below! Pointer type parameters in C are also passed by value; Pointer type parameters in C are also passed by value;

of course the object pointed to may very well change of course the object pointed to may very well change during call, but that still keeps the pointer invariantduring call, but that still keeps the pointer invariant

C structs are passed by value, requiring a copy of the C structs are passed by value, requiring a copy of the actual struct; that may be a large amount of data spaceactual struct; that may be a large amount of data space

How can a programmer pass an How can a programmer pass an array[] by value in Carray[] by value in C?? Pack array[] as a field into a struct, consumes identical Pack array[] as a field into a struct, consumes identical

amount of space as the original array[] modulo amount of space as the original array[] modulo padding; will all be copied at place and moment of callpadding; will all be copied at place and moment of call

12

Value Parameter in C++ C++ inherits C’s parameter passing methodsC++ inherits C’s parameter passing methods Hence the default parameter passing method in C++ Hence the default parameter passing method in C++

is also by valueis also by value But C++ adds the explicit reference parameter type, But C++ adds the explicit reference parameter type,

using the optional using the optional && operator for formal reference operator for formal reference parametersparameters

13

Value Parameter in C, Sample Set-Up

#define ASSERT( condition, msg, value ) \#define ASSERT( condition, msg, value ) \ if ( ! ( condition ) ) { \if ( ! ( condition ) ) { \ printf( "<> error: %s. Instead: %d\n", msg, value );\printf( "<> error: %s. Instead: %d\n", msg, value );\ } //end if} //end if

typedef struct { int field; } typedef struct { int field; } struct_tpstruct_tp;;typedef int * typedef int * int_ptrint_ptr;;

int global1 = 109;int global1 = 109;int global2 = 2012;int global2 = 2012;

14

Value int Parameter in C// assignment to formal VP has no impact on AP// assignment to formal VP has no impact on APvoid change_int_val( int value )void change_int_val( int value ){ // change_int_val{ // change_int_val ASSERT( 109 == value,ASSERT( 109 == value, "in change_int_val should be 109”, value );"in change_int_val should be 109”, value ); value++;value++; // change formal parameter (FP)// change formal parameter (FP) ASSERT( 110 == value,ASSERT( 110 == value, "in change_int_val should be 110”, value );"in change_int_val should be 110”, value );} //end change_int_val} //end change_int_val

void int_val( void )void int_val( void ){ // int_val{ // int_val int local1 = 109;int local1 = 109; change_int_val( local1 );change_int_val( local1 ); ASSERT( ( 109 == local1 ), should be 109", local1 );ASSERT( ( 109 == local1 ), should be 109", local1 );} //end int_val} //end int_val

15

Value struct Parameter in C// assign to formal value struct param no impact on actual// assign to formal value struct param no impact on actualvoid change_struct_val( void change_struct_val( struct_tpstruct_tp value ) value ){ // change_struct_val{ // change_struct_val ASSERT( 109 == value.field,ASSERT( 109 == value.field, "in change_struct_vale should be 109”,"in change_struct_vale should be 109”, value.field );value.field ); value.field++; // change formalvalue.field++; // change formal ASSERT( 110 == value.field,ASSERT( 110 == value.field, "in change_struct_val should be 110”,"in change_struct_val should be 110”, value.field );value.field );} //end change_struct_val} //end change_struct_val

void struct_val( void )void struct_val( void ){ // struct_val{ // struct_val struct_tpstruct_tp local1; local1; local1.field = 109;local1.field = 109; change_struct_val( local1 );change_struct_val( local1 ); ASSERT( ( 109 == local1.field ),ASSERT( ( 109 == local1.field ), "struct field should be 109", local1.field );"struct field should be 109", local1.field );} //end struct_val} //end struct_val

16

Value pointer Parameter in C// assign to formal ptr value param has no impact on actual// assign to formal ptr value param has no impact on actualvoid change_ptr_val( void change_ptr_val( int_ptrint_ptr value ) value ){ // change_ptr_val{ // change_ptr_val ASSERT( ASSERT( 109 == *value109 == *value,, "in change_ptr_val should be 109", *value );"in change_ptr_val should be 109", *value ); value = & global2; // formal parameter change!value = & global2; // formal parameter change! ASSERT( *value == 2012,ASSERT( *value == 2012, "pointed-to should be 2012", *value );"pointed-to should be 2012", *value );} //end change_ptr_val} //end change_ptr_val

void ptr_val( void )void ptr_val( void ){ // ptr_val{ // ptr_val int_ptrint_ptr local1 = & global1; local1 = & global1; // init to 109// init to 109 ASSERT( local1 == & global1,ASSERT( local1 == & global1, "before: should be & global1", & global1 ); "before: should be & global1", & global1 ); change_ptr_val( local1 ); change_ptr_val( local1 ); ASSERT( local1 == & global1,ASSERT( local1 == & global1, "Wrong pointer; points to:", *local1 );"Wrong pointer; points to:", *local1 ); ASSERT( 109 == *local1,ASSERT( 109 == *local1, "pointed-to value should be 109", *local1 );"pointed-to value should be 109", *local1 );} //end ptr_val} //end ptr_val

17

Reference Parameter (RP) The AP for RP passing must be a named object; The AP for RP passing must be a named object;

cannot be an expressioncannot be an expression

AP does not have to be initialized, but the callée AP does not have to be initialized, but the callée better abstain from referencing before assigningbetter abstain from referencing before assigning

Goal is for callée eventually to compute and then Goal is for callée eventually to compute and then return a new value in the APreturn a new value in the AP

Assignments to the formal RP have an immediate Assignments to the formal RP have an immediate impact on the AP, since impact on the AP, since FP and AP are aliased FP and AP are aliased to to one another in RP passingone another in RP passing

Aliasing may be a source of hard to track errorsAliasing may be a source of hard to track errors

Implement RP by passing the address of the AP; Implement RP by passing the address of the AP; hence it is clear that the AP must be an addressable hence it is clear that the AP must be an addressable object; other implementations possible, specifically: object; other implementations possible, specifically: passing address in registerpassing address in register

18

Reference Parameter in C++, Set-Up#include <iostream>#include <iostream>

#define ASSERT( condition, msg, value ) \#define ASSERT( condition, msg, value ) \ if ( ! ( condition ) ) { \if ( ! ( condition ) ) { \ printf( "<> error: %s. Instead: %d\n", \printf( "<> error: %s. Instead: %d\n", \ msg, ( value ) ); \msg, ( value ) ); \ } }

#define MAX 10#define MAX 10

typedef struct {typedef struct { // create struct w. 1 int field// create struct w. 1 int field int field;int field; // due to size = 4 -> no padding// due to size = 4 -> no padding} } struct_tpstruct_tp;;

typedef int typedef int arr_tparr_tp[ MAX ];[ MAX ];typedef int * typedef int * int_ptrint_ptr;;

// some globally visible variables// some globally visible variablesint global1 = 109;int global1 = 109;int global2 = 2013;int global2 = 2013;

19

Reference int Parameter in C++// assignment to formal impacts actual// assignment to formal impacts actualvoid change_int_ref( int & value )void change_int_ref( int & value ){ // change_int_ref{ // change_int_ref ASSERT( ASSERT( 109 == value109 == value,, "in change_int_ref should be 109”, value );"in change_int_ref should be 109”, value ); value++; value++; // change formal, implied deref// change formal, implied deref ASSERT( ASSERT( 110 == value110 == value,, "in change_int_ref should be 110”, value );"in change_int_ref should be 110”, value );} //end change_int_ref} //end change_int_ref

void int_ref( void )void int_ref( void ){ // int_ref{ // int_ref int local1 = 109;int local1 = 109; change_int_ref( local1 );change_int_ref( local1 ); ASSERT( ( 110 == local1 ),ASSERT( ( 110 == local1 ), "int should be 110", local1 );"int should be 110", local1 );} //end int_ref} //end int_ref

20

Reference struct Parameter in C++// assign to formal "ref struct param" impacts actual// assign to formal "ref struct param" impacts actualvoid change_struct_ref( void change_struct_ref( struct_tpstruct_tp && value ) value ){ // change_struct_ref{ // change_struct_ref ASSERT( 109 == value.field,ASSERT( 109 == value.field, // implied deref!!!// implied deref!!! "in change_struct_ref should be 109”,"in change_struct_ref should be 109”, value.field );value.field ); value.field++; // change formalvalue.field++; // change formal ASSERT( 110 == value.field,ASSERT( 110 == value.field, "in change_struct_ref should be 110”,"in change_struct_ref should be 110”, value.field );value.field );} //end change_struct_ref} //end change_struct_ref

void struct_ref( void )void struct_ref( void ){ // struct_ref{ // struct_ref struct_tp local1;struct_tp local1; local1.field = 109;local1.field = 109; change_struct_ref( local1 );change_struct_ref( local1 ); ASSERT( ( 110 == local1.field ),ASSERT( ( 110 == local1.field ), "struct field should be 110", local1.field );"struct field should be 110", local1.field );} //end struct_ref} //end struct_ref

21

Reference pointer Parameter in C++// assign to formal "ref ptr param" impacts actual// assign to formal "ref ptr param" impacts actualvoid change_ptr_ref( void change_ptr_ref( int_ptrint_ptr && value ) value ){ // change_ptr_ref{ // change_ptr_ref ASSERT( ASSERT( 109 == *value109 == *value,, "pointer-to should be 109", *value );"pointer-to should be 109", *value ); value = & global2; // formal value changedvalue = & global2; // formal value changed ASSERT( *value == 2013,ASSERT( *value == 2013, "pointed-to should be 2013", *value );"pointed-to should be 2013", *value );} //end change_ptr_ref} //end change_ptr_ref

void ptr_ref( void )void ptr_ref( void ){ // ptr_ref{ // ptr_ref int_ptr local1 = & global1;int_ptr local1 = & global1; ASSERT( 109 == *local1,ASSERT( 109 == *local1, "pointer-to should be 109 in ptr_ref", *local1 );"pointer-to should be 109 in ptr_ref", *local1 ); change_ptr_ref( local1 );change_ptr_ref( local1 ); ASSERT( local1 == & global2,ASSERT( local1 == & global2, "Wrong pointer; points to:", *local1 );"Wrong pointer; points to:", *local1 ); ASSERT( 2013 == *local1,ASSERT( 2013 == *local1, "pointed-to value should be 2013", *local1 );"pointed-to value should be 2013", *local1 );} //end ptr_ref} //end ptr_ref

22

No Ref array[] Parameters in C++// assign to formal "array param" impacts actual// assign to formal "array param" impacts actualvoid change_arr_ref( void change_arr_ref( arr_tparr_tp value ) // value ) // ref. is default!!ref. is default!!{ // change_arr_ref{ // change_arr_ref ASSERT( value[ 5 ] == 109,ASSERT( value[ 5 ] == 109, "value[ 5 ] should be 109", value[ 5 ] );"value[ 5 ] should be 109", value[ 5 ] ); value[ 5 ]++; // formal value changedvalue[ 5 ]++; // formal value changed ASSERT( value[ 5 ] == 110,ASSERT( value[ 5 ] == 110, "value[5] should be 110 in change()”, value[5] );"value[5] should be 110 in change()”, value[5] );} //end change_arr_ref} //end change_arr_ref

void arr_ref( void )void arr_ref( void ){ // arr_ref{ // arr_ref arr_tp value;arr_tp value; for ( int i=0; i < MAX; i++ ) { value[i] = 109; }for ( int i=0; i < MAX; i++ ) { value[i] = 109; } ASSERT( 109 == value[ 5 ],ASSERT( 109 == value[ 5 ], "value[5] should be 109 in arr_ref", value[5] );"value[5] should be 109 in arr_ref", value[5] ); change_arr_ref( value );change_arr_ref( value ); ASSERT( 110 == value[ 5 ],ASSERT( 110 == value[ 5 ], "value[ 5 ] should be 110", value[ 5 ] );"value[ 5 ] should be 110", value[ 5 ] );} //end arr_ref} //end arr_ref

23

Value-Result Parameter in Fortran AP must be addressable object, to be bound to FPAP must be addressable object, to be bound to FP

Assignments to FP are allowed in calléeAssignments to FP are allowed in callée

During the call, the AP is unchanged; note that this During the call, the AP is unchanged; note that this is quite is quite different from RP different from RP passing!passing!

At moment of return –and there may be many places At moment of return –and there may be many places in the code– the last value assigned to the FP is in the code– the last value assigned to the FP is copied back into the APcopied back into the AP

Not discussed further in CS 201Not discussed further in CS 201

Should be covered in Fortran programming class, or Should be covered in Fortran programming class, or compiler classcompiler class

24

Name Parameter in Algol60 Is default, quirky parameter passing method in Algo60Is default, quirky parameter passing method in Algo60

The The texttext of the AP substitutes the corresponding FP of the AP substitutes the corresponding FP for any particular callfor any particular call

Can have strange side-effectsCan have strange side-effects

Highly complicated to understand and implement, first Highly complicated to understand and implement, first done by Ingerman, using “done by Ingerman, using “thunksthunks””

Also not covered in CS 201; belongs into advanced Also not covered in CS 201; belongs into advanced Compiler classCompiler class

25

Name Parameter in Algol60Comment: Algol60 sample; definition of confuse()Comment: Algol60 sample; definition of confuse()procedure confuse( a, b )procedure confuse( a, b ) integer a, binteger a, b beginbegin b := 4;b := 4; a := 5;a := 5; end;end;

confuse( x[ i ], i ); comment: i = 33, x[33] = 10confuse( x[ i ], i ); comment: i = 33, x[33] = 10

Comment: as if confuse() had been coded like this:Comment: as if confuse() had been coded like this:procedure confuse( x[i], i )procedure confuse( x[i], i ) integer x[ i ], iinteger x[ i ], i beginbegin i := 4;i := 4; x[4] := 5;x[4] := 5; end;end;

Comment: x[33] is unaffected, i = 4, and x[4] = 5Comment: x[33] is unaffected, i = 4, and x[4] = 5

26

In-Out Parameter in Ada Is one of the parameter passing methods used in Is one of the parameter passing methods used in

Ada; close but Ada; close but not identical to not identical to value-result value-result parameter passingparameter passing

Is a combination of the in-parameter and out-Is a combination of the in-parameter and out-parameter passing methodsparameter passing methods

Similar to value-result parameter passing, but it is Similar to value-result parameter passing, but it is left unspecified at which moment the value of the FP left unspecified at which moment the value of the FP is copied back into the APis copied back into the AP

Will not be discussed in CS 201 Will not be discussed in CS 201

27

References

1. Revised Algol60 report: http://www.masswerk.at/algol60/report.htm

2. ADA reference manual: http://www.adaic.org/resources/add_content/standards/05rm/html/RM-TTL.html

3. Ada report: http://www.sigada.org/ada_95/what_is_ada.html

4. Fortran standard: http://www.j3-fortran.org

5. Fast Interprocedural Alias Analysis: Keith D. Cooper, Ken Kennedy, Dept. of CS, Rice University, NSF grant CCR 86-19893