39
1 CHAPTER 9 CHAPTER 9 SUBPROGRAM SUBPROGRAM

1 CHAPTER 9 SUBPROGRAM. 2 SUBPROGRAM Topics: b Definitions of subprogram b general subprogram characteristics b parameters b Functions and procedures

Embed Size (px)

Citation preview

1

CHAPTER 9CHAPTER 9SUBPROGRAMSUBPROGRAM

2

SUBPROGRAMSUBPROGRAM

Topics:Topics: Definitions of subprogramDefinitions of subprogram general subprogram characteristicsgeneral subprogram characteristics parametersparameters Functions and proceduresFunctions and procedures Design issues for subprogramDesign issues for subprogram Parameter passing methodParameter passing method Model for parameter passingModel for parameter passing Overload subprogramOverload subprogram Type checking & referencing environmentType checking & referencing environment Subprogram passed methodSubprogram passed method Generic subprogramGeneric subprogram

3

Definitions :Definitions :

Subprogram : Subprogram :

A program separate from the main program that executes aseries A program separate from the main program that executes aseries

Of operations that occures multiple times during the machine cycle.Of operations that occures multiple times during the machine cycle.

SubprogramSubprogram :: describes the interface to and the actions of the subprogram describes the interface to and the actions of the subprogram abstraction .abstraction .

SubprogramSubprogram callcall :: is the explicit request that the called subprograms beis the explicit request that the called subprograms be

executed . executed .

Process abstraction Process abstraction are presented in programming languages by are presented in programming languages by subprogramssubprograms

4

What does it mean for a subproram to be active ?What does it mean for a subproram to be active ?

SubprogramSubprogram :: is to be is to be activeactive if after having been called ,it has if after having been called ,it has

begun execution but has not yet completed that execution begun execution but has not yet completed that execution

Execution timeExecution time

Duration timeDuration time

Subprogram(x) startSubprogram(x) start

5

Definitions :Definitions :

AA SubprogramSubprogram headerheader ::

is the first line of the definition ,serves several purposes. First is is the first line of the definition ,serves several purposes. First is specifies that the following syntactic unit is a subprogram's kind specifies that the following syntactic unit is a subprogram's kind is often accomplished with a special word .is often accomplished with a special word .

The header contains some keyword signalin the beginning of The header contains some keyword signalin the beginning of asubproram, a name for the subprogram ,and Header it may asubproram, a name for the subprogram ,and Header it may optionally specify alist of parametersoptionally specify alist of parameters

e.ge.g: (Fortran) : (Fortran)

Subroutine Adder (parameters)Subroutine Adder (parameters)

6

e.g: (C)e.g: (C)

VoidVoid adder (parameters)adder (parameters)

,would serve as the header of a SUBPROGRAM named,would serve as the header of a SUBPROGRAM named

adderadder ,where,where voidvoid indicates that it does not return a value indicates that it does not return a value

PrototypePrototype ::is a subprogram declaration providing is a subprogram declaration providing

InterfaceInterface informationinformation

Definitions :Definitions :

7

Definitions :Definitions :

Parameter profile:Parameter profile:

Describes the number ,order , and types of the parametersDescribes the number ,order , and types of the parameters

**also called “signature”.**also called “signature”.

8

General subprogram characteristics : General subprogram characteristics :

Each subprogram has a single entry pointEach subprogram has a single entry point

The calling program unit is suspend during The execution of the called The calling program unit is suspend during The execution of the called subprogram , which means that there is only one subprogram in subprogram , which means that there is only one subprogram in execution at any timeexecution at any time

Control always return to the caller when the subprogram execution Control always return to the caller when the subprogram execution terminatesterminates

9

Parameters :Parameters :

There are two ways that subprogram can gain access to the data There are two ways that subprogram can gain access to the data that it is to process:that it is to process:

Direct access to nonlocal variablesDirect access to nonlocal variables Parameter passingParameter passing

** Parameter passing is more flexible than direct access to ** Parameter passing is more flexible than direct access to nonlocal variablesnonlocal variables

10

Formal parameters :Formal parameters :The parameters in the subprogram headerThe parameters in the subprogram header Actual parameters :Actual parameters :alist of parameters that appear in subprogram call statementalist of parameters that appear in subprogram call statement Positional Positional parameters:parameters: is a method for bindingis a method for binding actual parameter to formal parameter, is done by position actual parameter to formal parameter, is done by position

** ((the first actual parameters is bound to the first formal parameter and so forth ** ((the first actual parameters is bound to the first formal parameter and so forth such parameters are calledsuch parameters are called positional parameterspositional parameters ))))

e.g :e.g :M = rect (a , b ,c ) // subproram callM = rect (a , b ,c ) // subproram call

Float rect ( int x , int y , int z )Float rect ( int x , int y , int z )

Parameters : (count …) Parameters : (count …)

11

Keyword parameters :Keyword parameters :The name of the formal parameter to which an actual parameter is to be The name of the formal parameter to which an actual parameter is to be

bound is specified with the actual parameterbound is specified with the actual parameterAdvantage:Advantage:That they can appear in any order in the actual parameter list That they can appear in any order in the actual parameter list Disadvantage:Disadvantage:That the user of the subprogram must know the names of formal That the user of the subprogram must know the names of formal

parametersparameters

Parameters : (count …) Parameters : (count …)

12

Subprogram example:Subprogram example:

Int cube(int); prototypeInt cube(int); prototypeInt main(){Int main(){ Int y=5; actual parametersInt y=5; actual parameters Cout<<cube(y); Subprogram callCout<<cube(y); Subprogram call Int x=3;Int x=3; Int cube (int x); subprogram headerInt cube (int x); subprogram header{ { formal parameterformal parameterreturn x*x;return x*x;}}}}

13

The Two kinds of subprograms :The Two kinds of subprograms :

There are There are twotwo distinct categories of subprograms: distinct categories of subprograms:

ProceduresProcedures FunctionsFunctions

14

Procedures :Procedures :

Procedures Procedures :: are collection of statements that define parameterized computations ,are collection of statements that define parameterized computations , these computations are enacted by single call statements.these computations are enacted by single call statements.Procedure are calledProcedure are called subroutinessubroutines

Procedures has Two parts :Procedures has Two parts :The speification and the BodyThe speification and the BodyThe specification is begins with the keyword PROCEDURE and endsThe specification is begins with the keyword PROCEDURE and endsWith the procedure name or parameter listWith the procedure name or parameter list

e.G : e.G : PROCEDUREPROCEDURE a_test(a,b : in integer ; c:out Integer) a_test(a,b : in integer ; c:out Integer)

15

Procedures :Procedures :

Procedure identifier Rules :Procedure identifier Rules : The name must start with aletter or made out of lettersThe name must start with aletter or made out of letters

, numbers and the underscore( _ )., numbers and the underscore( _ ). the name is always case-sensetive ( uppercase / lowercase the name is always case-sensetive ( uppercase / lowercase

names are identical).names are identical). the name may not start with the dollar-sign ($).the name may not start with the dollar-sign ($).

16

Examples of proceduresExamples of procedures

Program Program example1;example1; SpecificationSpecification

procedure procedure add; add; varvar x : x : integer ;integer ; y : y : integer ;integer ;begin begin

BODYBODY read read ( x , y );( x , y ); write write ( x + y );( x + y );end;end;

BEGINBEGINadd;add;

END .END .

17

Functions :Functions :

FunctionsFunctions : : structurally resemble procedure, But are semantically structurally resemble procedure, But are semantically modeled on mathematical functions ( Functionsmodeled on mathematical functions ( Functions are procedures are procedures which return value).which return value).

** Function are** Function are calledcalled by appearances of their name in expressionsby appearances of their name in expressions

e.g: (function header and call )e.g: (function header and call )

VoidVoid sort (sort (intint list[],list[], intint listlen); // function headerlistlen); // function header

……

Sort(scores,100); // function callSort(scores,100); // function call

18

Functions :Functions :

**** In function body The return statement end the execution of In function body The return statement end the execution of

the function and return the value of the expression enclosed the function and return the value of the expression enclosed

In the braces as a resultIn the braces as a result

**The function body can contain any number of return **The function body can contain any number of return statementstatement

19

Functions :Functions :

// function example :// function example :

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

BeginBegin

If A<= B then If A<= B then

Return A ;Return A ;

Else Else

Return B ;Return B ;

End if ;End if ;

End minimum;End minimum;

20

Design Issues For Functions :Design Issues For Functions :

There are There are TwoTwo design issues are specific to functions : design issues are specific to functions :

Functional side effectFunctional side effectThe evaluation of a function effect the the value of other operands in the same The evaluation of a function effect the the value of other operands in the same

expression.expression.** (solution parameters to functios can have only in mode formal parameter)** (solution parameters to functios can have only in mode formal parameter) Types of returned valueTypes of returned valuemost imperative programming languages restrict the types that can be returned by most imperative programming languages restrict the types that can be returned by

their functions .their functions .• C allow any type to be returned by its function except arrays and functions “both C allow any type to be returned by its function except arrays and functions “both

of these can be handled by pointer type return values ”of these can be handled by pointer type return values ”• Ada language its function can return values of any type Ada language its function can return values of any type

21

QUESTIONS?QUESTIONS?

22

Design issues for subprogram :Design issues for subprogram :

What parameter passing method use ?What parameter passing method use ? Are the type of the actual parameter checked against the formal Are the type of the actual parameter checked against the formal

parameter ?parameter ? Are local variables statically or dynamically allocated?Are local variables statically or dynamically allocated? If subprogram can be passed as parameters what is the referencing If subprogram can be passed as parameters what is the referencing

environment of such subprogram ?environment of such subprogram ? Can subprogram be overloaded ?Can subprogram be overloaded ? Can subprogram be generic ?Can subprogram be generic ? Is either separate or independent compilation possible ?Is either separate or independent compilation possible ?

23

Parameter passing methods :Parameter passing methods :

Parameter passing methods are the ways in which parameters are Parameter passing methods are the ways in which parameters are transmitted to and/or from calling subprogram, transmitted to and/or from calling subprogram,

Formal parameters are characterized by one of three distinct Formal parameters are characterized by one of three distinct semantics models :semantics models :

1.1. They can receive data from the corresponding actual parameter (They can receive data from the corresponding actual parameter ( in in modemode).).

2.2. They can transmit data to the actual parameter (They can transmit data to the actual parameter (outout modemode).).

3.3. They can do both (They can do both (inout modeinout mode).).

24

Graph for parameter passing methods :Graph for parameter passing methods :

25

Implementation models for parameter passing :Implementation models for parameter passing :

Pass by valuePass by value Pass by resultPass by result Pass by value resultPass by value result Pass by referencePass by reference Pass by namePass by name

26

Pass by value :Pass by value :

When parameter is passed by value ,the value of the actual parameter is used When parameter is passed by value ,the value of the actual parameter is used to initialize the correspondin formal parameter ,which then act as alocal to initialize the correspondin formal parameter ,which then act as alocal variable in the subprogramvariable in the subprogram

Advantage:Advantage: simple mechanism,actual parameter can be expression or simple mechanism,actual parameter can be expression or values, (formal parameters are write protected) does not cause side effectvalues, (formal parameters are write protected) does not cause side effect..

Disadvantage:Disadvantage: needs additional storage for formal parameters .needs additional storage for formal parameters .

27

Pass by result :Pass by result :

Formal parameter acts as local variable just before control returns to caller , Formal parameter acts as local variable just before control returns to caller , value is passed to actual parameter , which must be a variablevalue is passed to actual parameter , which must be a variable

problem #1:problem #1:Actual parameter collision , such as call sub(p1,p1) may return different values to Actual parameter collision , such as call sub(p1,p1) may return different values to

p1 depending on order of assignmentp1 depending on order of assignment Problem #2:Problem #2:Address evaluation may be done at call or at return, for example list[index] if the 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 index is changed by the subprogram ,either through global access or as formal parameter ,ten the address of list[index] will changed between the call and the parameter ,ten the address of list[index] will changed between the call and the returnreturn

28

Pass by value result :Pass by value result :

The value of the actual parameter is used to initialize the corresponding The value of the actual parameter is used to initialize the corresponding formal parameter ,the value of the formal parameter is transmitted back formal parameter ,the value of the formal parameter is transmitted back to the actual parameterto the actual parameter

Pass by value result is some times callPass by value result is some times call pass by copypass by copy

Pass by value resultPass by value result shareshare withwith pass by valuepass by value and pass by result the and pass by result the disadvantage of requiring multiple storage for parameters and time for disadvantage of requiring multiple storage for parameters and time for copying values .copying values .

Pass by value resultPass by value result shareshare withwith pass by resultpass by result the problems associated the problems associated with the order in which actual parameters are assigned .with the order in which actual parameters are assigned .

29

Pass by reference :Pass by reference :

In pass by reference method transmits an access path ,usually just an In pass by reference method transmits an access path ,usually just an address , to the called subprogram address , to the called subprogram

The called subprogram is allowed to access the actual parameter in the The called subprogram is allowed to access the actual parameter in the calling program unit .calling program unit .

30

Pass by reference : (count …)Pass by reference : (count …)

The The advantageadvantage of Pass by reference : of Pass by reference : Passing process is efficient , in term of both time and space , duplicate space is not Passing process is efficient , in term of both time and space , duplicate space is not required , nor is any copying required .required , nor is any copying required .

The The disadvantagedisadvantage of Pass by reference : of Pass by reference :

11. . access to the formal parameters will be slower ,because of the additional level of access to the formal parameters will be slower ,because of the additional level of indirect addressing that is requiredindirect addressing that is required

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

3. the aliases can be created3. the aliases can be created

31

Pass by name :Pass by name :

The actual parameter is textually substituted for the formal parameter in The actual parameter is textually substituted for the formal parameter in all its occurrences in the subprogram .all its occurrences in the subprogram .

Advantage:Advantage: More flexible than other methods.More flexible than other methods.

Disadvantage :Disadvantage : Relatively slow than other methods Relatively slow than other methods Very expensiveVery expensive

32

Parameter passing example:Parameter passing example:

Program ParamPassing;vari : integer;a : array[1..2] of integer;

procedure p(x, y : integer);beginx := x + 1;i := i + 1;y := y + 1;end; {p}

begin {ParamPassing}a[1] := 1;a[2] := 1;i := 1;p(a[i], a[i]);writeln(‘a[1] = ’, a[1]);writeln(‘a[2] = ’, a[2]);end.

Pass by value:a[1] = 1a[2] = 1

Pass by result:x and y have no initial values

Pass by value-result:a[1] = 2a[2] = 1

Pass by reference:a[1] = 3a[2] = 1

Pass by name:a[1] = 2a[2] = 2

33

Overload SubprogramOverload Subprogram

Overload SubprogramOverload Subprogram is a subprogram that has the same name as is a subprogram that has the same name as another subprogram in the same referencing environmentanother subprogram in the same referencing environment

Overloaded subprograms that have default parameters can lead to Overloaded subprograms that have default parameters can lead to ambiguous subprogram calls.ambiguous subprogram calls.

Example: (C++)Example: (C++)void fun( float b = 0.0 );void fun( float b = 0.0 );void fun();void fun();……fun ( );fun ( );

34

QUESTIONS?QUESTIONS?

35

Type checking parameter :Type checking parameter :

Without type checking ,some typographical errors lead to program Without type checking ,some typographical errors lead to program error difficult to diagnose because they are not detected by the error difficult to diagnose because they are not detected by the compiler or the run time system.compiler or the run time system.

Early programming language ,such as FORTRAN 77 and the Early programming language ,such as FORTRAN 77 and the original version of c did not required parameter type original version of c did not required parameter type checking ,most later language require it , the relatively recent checking ,most later language require it , the relatively recent language Perl, JavaScript , and PHP do not language Perl, JavaScript , and PHP do not

36

Example of type checking parameter :Example of type checking parameter :

double double sin(x)sin(x)doubledouble x; x;{ …. }{ …. }

Using this method avoids type checking, thereby allowing calls such as:Using this method avoids type checking, thereby allowing calls such as:

Double Double value;value;int int count;count;……Value = sin (count);Value = sin (count);

To be legal, although they are never correctTo be legal, although they are never correct

37

Subprogram passed as parameters:Subprogram passed as parameters:

Some language allow nested subprogramSome language allow nested subprogram ((allow subprogram ((allow subprogram to be a parameter for another subprogram))to be a parameter for another subprogram))

So in this case the following choices for referencing So in this case the following choices for referencing environment:environment:

1.1. Shallow bindingShallow binding : : the environment of the call statement the environment of the call statement that enacts the passed subprogram.that enacts the passed subprogram.

2.2. Deep bindingDeep binding :: the environment of the definition the environment of the definition

of the passed subprogramof the passed subprogram . .

3.3. Ad hoc bindingAd hoc binding : : the environment of the call statement that the environment of the call statement that passed the subprogram as an actual parameterpassed the subprogram as an actual parameter

38

Generic SubprogramGeneric Subprogram

A genericA generic oror polymorphicpolymorphic subprogram is one that takes parameters subprogram is one that takes parameters of different types on different activations.of different types on different activations.

Overloaded subprograms provideOverloaded subprograms provide ad hoc polymorphism ad hoc polymorphism .. A subprogram that takes a generic parameter that is used in a type A subprogram that takes a generic parameter that is used in a type

expression that describes the type of the parameters of the expression that describes the type of the parameters of the subprogram providessubprogram provides parametric polymorphism parametric polymorphism ..

39

Advantages to using subprogramsAdvantages to using subprograms

There are several advantages to using subprogramsThere are several advantages to using subprograms: : They help keep the code simple, and, thus, more readable; They help keep the code simple, and, thus, more readable; They allow the programmer to use the same code as many times as needed They allow the programmer to use the same code as many times as needed

throughout the program; throughout the program; They allow the programmer to define needed functions; and, They allow the programmer to define needed functions; and, They can be used in other programs They can be used in other programs