Sunteți pe pagina 1din 17

Subroutine

From Wikipedia, the free encyclopedia


(Redirected from Procedure (computer science))

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may bechallenged and removed. (February
2013)

In computer programming, a subroutine is a sequence of program instructions that perform a specific task, packaged as a unit !his unit can then be used in programs "here#er that particular task should be performed Subprograms may be defined "ithin programs, or separately in libraries that can be used by multiple programs In different programming languages a subroutine may be called aprocedure, a function, a routine, a method, or a subprogram !he generic term callable unit is sometimes used $%& 's the name subprogram suggests, a subroutine beha#es in much the same "ay as a computer program that is used as one step in a larger program or another subprogram ' subroutine is often coded so that it can be started (called) se#eral times and(or from se#eral places during one e)ecution of the program, including from other subroutines, and then branch back (return) to the ne)t instruction after the call once the subroutine*s task is done +aurice Wilkes, ,a#id Wheeler, and Stanley -ill are credited "ith the in#ention of this concept, "hich they termed a closed subroutine,$.& contrasted "ith an open subroutine or macro $/& Subroutines are a po"erful programming tool,$0& and the synta) of many programming languages includes support for "riting and using them 1udicious use of subroutines (for e)ample, through the structured programming approach) "ill often substantially reduce the cost of de#eloping and maintaining a large program, "hile increasing its quality and reliability
$2&

Subroutines, often collected into libraries, are an important

mechanism for sharing and trading soft"are !he discipline of ob3ect4oriented programming is based on ob3ects and methods ("hich are subroutines attached to these ob3ects or ob3ect classes) In the compiling method called threaded code, the e)ecutable program is basically a sequence of subroutine calls
Contents
[hide]

1 Main concepts

2 Language support 3 dvantages ! "isadvantages # $istory

o o o o o o o

#.1 Language support #.2 %el&'modi&ying code #.3 %ubroutine libraries #.! (eturn by indirect )ump #.# *ump to subroutine #.+ ,all stac#.. "elayed stac-ing + , and ,// e0amples . 1isual 2asic + e0amples 3 PL45 e0ample 6 Local variables7 recursion and

reentrancy 18 9verloading 11 ,losures 12 ,onventions

12.1 (eturn codes 13 9ptimi:ation o& subroutine calls

13.1 5nlining 1! %ee also

1# (e&erences

$edit&+ain

concepts

!he content of a subroutine is its body, the piece of program code that is e)ecuted "hen the subroutine is called or invoked ' subroutine may be "ritten so that it e)pects to obtain one or more data #alues from the calling program (its parameters orformal parameters) !he calling program pro#ides actual #alues for these parameters, called arguments ,ifferent programming languages may use different con#entions for passing arguments5

Convention

Description

Common use

,all by value

rgument is evaluated andcopy o& value is passed to subroutine

,7 *ava

,all by re&erence (e&erence to argument7 typically its address is passed

;ortran7 PL45

,all by result

Parameter value is copied bac- to argument on return &rom the subroutine

da 9UT parameters

,all by value' result

Parameter value is copied bac- on entry to the subroutine and again on return

lgol

,all by name

Li-e a macro < replace the parameters =ith the unevaluated argumentexpressions

lgol

,all by constant Li-e call by value e0cept that the parameter is treated value as a constant

PL45 >9> %%5?> 2L@ parameters7 da 5> parameters

!he subroutine may also return a computed #alue to its caller (its return value), or pro#ide #arious result #alues or out(put) parameters Indeed, a common use of subroutines is to implement mathematical functions, in "hich the purpose of the subroutine is purely to compute one or more results "hich #alues are entirely determined by the parameters passed to the subroutine (6)amples might include computing the logarithm of a number or the determinant of a matri) )

7o"e#er, a subroutine call may also ha#e side effects, such as modifying data structures in a computer memory, reading from or "riting to a peripheral de#ice, creating a file, halting the program or the machine, or e#en delaying the program*s e)ecution for a specified time ' subprogram "ith side effects may return different results each time it is called, e#en if it is called "ith the same arguments 'n e)ample is a random number function, a#ailable in many languages, that returns a different random4looking number each time it is called !he "idespread use of subroutines "ith side effects is a characteristic of imperati#e programminglanguages ' subroutine can be coded so that it may call itself recursi#ely, at one or more places, to perform its task !his method allo"s direct implementation of functions defined by mathematical inductionand recursi#e di#ide and conquer algorithms ' subroutine "hich purpose is to compute one boolean4#alued function (that is, to ans"er a yes(no question) is called apredicate In logic programming languages, often$vague& all subroutines are called predicates, since they primarily$vague&determine success or failure main()
$citation needed&

For e)ample, any type of function is a subroutine but not

$edit&8anguage

support

7igh4le#el programming languages usually include specific constructs to5

delimit the part of the program (body) that makes up the subroutine assign an identifier (name) to the subroutine specify the names and(or data types of its parameters and(or return #alues pro#ide a pri#ate naming scope for its temporary #ariables identify #ariables outside the subroutine that are accessible "ithin it call the subroutine pro#ide #alues to its parameters specify the return #alues from "ithin its body return to the calling program dispose of the #alues returned by a call handle any e)ceptional conditions encountered during the call package subroutines into a module, library, ob3ect, class, etc

Some programming languages, such as 9isual :asic ;6!,Pascal, Fortran, and 'da, distinguish bet"een functions orfunction subprograms, "hich pro#ide an e)plicit return #alue to the calling program, and subroutines or procedures, "hich do not In those languages, function calls are normally embedded ine)pressions (e g , a sqrt function may be called as y = z + sqrt(x))< "hereas procedure calls beha#e syntactically asstatements (e g , a print procedure may be called as if x > 0 then print(x) =ther languages, such as > and 8isp, do not make this distinction, and treat those terms as synonymous In strictly functional programming languages such as 7askell, subprograms can ha#e no side effects, and "ill al"ays return the same result if repeatedly called "ith the same arguments Such languages typically only support functions, since subroutines that do not return a #alue ha#e no use unless they can cause a side effect In programming languages such as >, >??, and >@, subroutines may also simply be called functions, not to be confused "ithmathematical functions or functional programming, "hich are different concepts ' language*s compiler "ill usually translate procedure calls and returns into machine instructions according to a "ell4definedcalling convention, so that subroutines can be compiled separately from the programs that call them !he instruction sequences corresponding to call and return statements are called the procedure*s prologue and epilogue

$edit&'d#antages
!he ad#antages of breaking a program into subroutines include5

decomposing a comple) programming task into simpler steps5 this is one of the t"o main tools of structured programming, along "ith data structures reducing duplicate code "ithin a program enabling reuse of code across multiple programs di#iding a large programming task among #arious programmers, or #arious stages of a pro3ect hiding implementation details from users of the subroutine impro#ing traceability, i e most languages offer "ays to obtain the call trace "hich includes the names of the in#ol#ed subroutines and perhaps e#en more information such as file names and line numbers< by not decomposing the code into subroutines, debugging "ould be impaired se#erely

$edit&,isad#antages
In#oking a subroutine (#ersus using in4line code) imposes somecomputational o#erhead in the call mechanism

!he subroutine typically requires standard housekeeping code A both at entry to, and e)it from, the function (function prologue and epilogue A usually sa#ing general purpose registers and return address as a minimum)

$edit&7istory $edit&Language

support

In the (#ery) early assemblers, subroutine support "as limited Subroutines "ere not e)plicitly separated from each other or from the main program, and indeed the source code of a subroutine could be interspersed "ith that of other subprograms Some assemblers "ould offer predefined macros to generate the call and return sequences 8ater assemblers (%BCDs) had much more sophisticated support for both in4line and separately assembled subroutines that could be linked together

$edit&Self-modifying

code

!he first use of subprograms "as on early computers that "ere programmed in machine code or assembly language, and did not ha#e a specific call instruction $citation needed& =n those computers, each subroutine call had to be implemented as a sequence of lo"er le#el machine instructions that relied on self4modifying code :y replacing the operand of a branch instructionat the end of the procedure*s body, e)ecution could then be returned to the proper location (designated by the return address) in the calling program (usually 3ust after the instruction that 3umped into the subroutine)

$edit&Subroutine

libraries

6#en "ith this cumbersome approach, subroutines pro#ed #ery useful For one thing they allo"ed the same code to be used in many different programs +ore#er, memory "as a #ery scarce resource on early computers, and subroutines allo"ed significant sa#ings in program siEe In many early computers, the program instructions "ere entered into memory from a punched paper tape 6ach subroutine could then be pro#ided by a separate piece of tape, loaded or spliced before or after the main program< and the same subroutine tape could then be used by many different programs ' similar approach "as used in computers "hich main input "as throughpunched cards !he name subroutine library originally meant a library, in the literal sense, "hich kept inde)ed collections of such tapes or card decks for collecti#e use

$edit&Return

by indirect jump

!o remo#e the need for self4modifying code, computer designers e#entually pro#ided an indirect jump instruction, "hich operand, instead of being the return address itself, "as the location of a #ariable or processor register containing the return address

=n those computers, instead of modifying the subroutine*s return 3ump, the calling program "ould store the return address in a #ariable so that "hen the subroutine completed, it "ould e)ecute an indirect 3ump that "ould direct e)ecution to the location gi#en by the predefined #ariable

$edit&Jump

to subroutine

'nother ad#ance "as the jump to subroutine instruction, "hich combined the sa#ing of the return address "ith the calling 3ump, thereby minimiEing o#erhead significantly In the I:+ System(/CD, for e)ample, the branch instructions :'8 or :'8R, designed for procedure calling, "ould sa#e the return address in a processor register specified in the instruction !o return, the subroutine had only to e)ecute an indirect branch instruction (:R) through that register If the subroutine needed that register for some other purpose (such as calling another subroutine), it "ould sa#e the register*s contents to a pri#ate memory location or a register stack In the 7P .%DD, the 1S: instruction "ould perform a similar task, e)cept that the return address "as stored in the memory location that "as the target of the branch 6)ecution of the procedure "ould actually begin at the ne)t memory location In the 7P .%DD assembly language, one "ould "rite, for e)ample

... JSB MYSUB BB ... (Calls s !ro tine MYSUB.) ("ill ret rn here after MYSUB is #one.)

to call a subroutine called +FSG: from the main program !he subroutine "ould be coded as

MYSUB $%& )) ... ... JM& MYSUB*+

(Stora'e for MYSUB(s ret rn a##ress.) (Start of MYSUB(s !o#y.) (,et rns to the -allin' pro'ra..)

!he 1S: instruction placed the address of the ;6H! instruction (namely, ::) into the location specified as its operand (namely, +FSG:), and then branched to the ;6H! location after that (namely, '' I +FSG: ? %) !he subroutine could then return to the main program by e)ecuting the indirect 3ump 1+P +FSG:,I "hich branched to the location stored at location +FSG: >ompilers for Fortran and other languages could easily make use of these instructions "hen a#ailable !his approach supported multiple le#els of calls< ho"e#er, since the return address, parameters, and return #alues of a subroutine "ere assigned fi)ed memory locations, it did not allo" for recursi#e calls

Incidentally, a similar method "as used by 8otus %4.4/, in the early %BJDs, to disco#er the recalculation dependencies in a spreadsheet ;amely, a location "as reser#ed in each cell to store the return address Since circular references are not allo"ed for natural recalculation order, this allo"s a tree "alk "ithout reser#ing space for a stack in memory, "hich "as #ery limited on small computers such as the I:+ P>

$edit&Call

stack

+ost modern implementations use a call stack, a special case of the stack data structure, to implement subroutine calls and returns 6ach procedure call creates a ne" entry, called a stack frame, at the top of the stack< "hen the procedure returns, its stack frame is deleted from the stack, and its space may be used for other procedure calls 6ach stack frame contains the private data of the corresponding call, "hich typically includes the procedure*s parameters and internal #ariables, and the return address !he call sequence can be implemented by a sequence of ordinary instructions (an approach still used in reduced instruction set computing (RIS>) and #ery long instruction "ord (98IW) architectures), but many traditional machines designed since the late %BCDs ha#e included special instructions for that purpose !he call stack is usually implemented as a contiguous area of memory It is an arbitrary design choice "hether the bottom of the stack is the lo"est or highest address "ithin this area, so that the stack may gro" for"ards or back"ards in memory< ho"e#er, many architectures chose the latter
$citation needed&

Some designs, notably some Forth implementations, used t"o separate stacks, one mainly for control information (like return addresses and loop counters) and the other for data !he former "as, or "orked like, a call stack and "as only indirectly accessible to the programmer through other language constructs "hile the latter "as more directly accessible When stack4based procedure calls "ere first introduced, an important moti#ation "as to sa#e precious memory $citation needed&With this scheme, the compiler does not ha#e to reser#e separate space in memory for the pri#ate data (parameters, return address, and local #ariables) of each procedure 't any moment, the stack contains only the pri#ate data of the calls that are currently active(namely, "hich ha#e been called but ha#en*t returned yet) :ecause of the "ays in "hich programs "ere usually assembled from libraries, it "as (and still is) not uncommon to find programs that include thousands of subroutines, of "hich only a handful are acti#e at any gi#en moment $citation needed& For such programs, the call stack mechanism could sa#e significant amounts of memory Indeed, the call stack mechanism can be #ie"ed as the earliest and simplest method for automatic memory management 7o"e#er, another ad#antage of the call stack method is that it allo"s recursi#e subroutine calls, since each nested call to the same procedure gets a separate instance of its pri#ate data

$edit&Delayed

stacking

=ne disad#antage of the call stack mechanism is the increased cost of a procedure call and its matching return !he e)tra cost includes incrementing and decrementing the stack pointer (and, in some architectures, checking for stack o#erflo"), and accessing the local #ariables and parameters by frame4relati#e addresses, instead of absolute addresses !he cost may be realiEed in increased e)ecution time, or increased processor comple)ity, or both !his o#erhead is most ob#ious and ob3ectionable in leaf procedures or leaf functions, "hich return "ithout making any procedure calls themsel#es $C&$K&$J& !o reduce that o#erhead, many modern compilers try to delay the use of a call stack until it is really needed
$citation needed&

For e)ample, the call of a procedureP may store the return

address and parameters of the called procedure in certain processor registers, and transfer control to the procedure*s body by a simple 3ump If procedure P returns "ithout making any other call, the call stack is not used at all IfP needs to call another procedure Q, it "ill then use the call stack to sa#e the contents of any registers (such as the return address) that "ill be needed after Q returns

$edit&>

and >?? e)amples

In the > and >?? programming languages, subprograms are termed functions (or member functions "hen associated "ith aclass) !hese languages use the special key"ord /oi# to indicate that a function takes no parameters (especially in >) and(or does not return any #alue ;ote that >(>?? functions can ha#e side4effects, including modifying any #ariables "hich addresses are passed as parameters (i e passed by reference) 6)amples5 /oi# f n-tion0(/oi#) 1 /* some code */ 2 !he function does not return a #alue and has to be called as a stand4alone function, e g , f n-tion0()3 int f n-tion4(/oi#) 1 ret rn 53 2 !his function returns a result (the number 2), and the call can be part of an e)pression, e g , x +

f n-tion4()
-har f n-tion6(int n .!er) 1 -har sele-tion78 = 1(S(*(M(*(9(*("(*(9(*(:(*(S(23 ret rn sele-tion7n .!er83 2

!his function con#erts a number bet"een D to C into the initial letter of the corresponding day of the "eek, namely D to *S*, % to *+*, , C to *S* !he result of calling it might be assigned to a #ariable, e g , n .;#ay =

f n-tion6(n .!er)3
/oi# f n-tion<(int =pointer;to;/ar) 1 (=pointer;to;/ar)++3 2 !his function does not return a #alue but modifies the #ariable "hich address is passed as the parameter< it "ould be called "ith Lf n-tion<(>/aria!le;to;in-re.ent)3L

$edit&9isual

:asic C e)amples

In the 9isual :asic C language, subprograms are termedfunctions or subs (or methods "hen associated "ith a class) 9isual :asic C uses #arious terms called types to define "hat is being passed as a parameter :y default, an unspecified #ariable is registered as a #ariant type and can be passed as ByRef(default) or ByVal 'lso, "hen a function or sub is declared, it is gi#en a public, pri#ate, or friend designation, "hich determines "hether it can be accessed outside the module and(or pro3ect that it "as declared in

By value By!al" A a "ay of passing the #alue of an argument to a procedure instead of passing the address !his allo"s the procedure to access a copy of the #ariable 's a result, the #ariable*s actual #alue can*t be changed by the procedure to "hich it is passed

By reference ByRef" A a "ay of passing the address of an argument to a procedure instead of passing the #alue !his allo"s the procedure to access the actual #ariable 's a result, the #ariable*s actual #alue can be changed by the procedure to "hich it is passed Gnless other"ise specified, arguments are passed by reference

#ublic (optional) A indicates that the function procedure is accessible to all other procedures in all modules If used in a module that contains an =ption Pri#ate, the procedure is not a#ailable outside the pro3ect

#rivate (optional) A indicates that the function procedure is accessible only to other procedures in the module "here it is declared

$riend (optional) A used only in a class module Indicates that the Function procedure is #isible throughout the pro3ect, but not #isible to a controller of an instance of an ob3ect

Private Function : n-tion0() ( So.e Co#e ?ere End Function

!he function does not return a #alue and has to be called as a stand4alone function, e g , : n-tion0 Private Function : n-tion4() as Integer : n-tion4 = 5 End Function !his function returns a result (the number 2), and the call can be part of an e)pression, e g , x +

: n-tion4()
Private Function : n-tion6(ByVal int@al e as Integer) as String Dim str)rray(A) as String str)rray = )rray(BMB* B9B* B"B* B9B* B:B* BSB* BSB) : n-tion6 = str)rray(int@al e) End Function !his function con#erts a number bet"een D and C into the initial letter of the corresponding day of the "eek, namely D to *+*, % to *!*, , C to *S* !he result of calling it might be assigned to a #ariable, e g , n .;#ay =

: n-tion6(n .!er)
Private Function : n-tion<(ByRef int@al e as Integer) int@al e = int@al e + 0 End Function !his function does not return a #alue but modifies the #ariable "hich address is passed as the parameter< it "ould be called "ith L: n-tion<(/aria!le;to;in-re.ent)L

$edit&P8(I

e)ample

In P8(I a called procedure may be passed a descriptor pro#iding information about the argument, such as string lengths and array bounds !his allo"s the procedure to be more general and eliminates the need for the programmer to pass such information :y default P8(I passes arguments by reference ' (tri#ial) subroutine to change the sign of each element of a t"o4dimensional array might look like5 -han'e;si'nC pro-e# re(array)3 #e-lare array(=*=) float3 array = Darray3 en# -han'e;si'n3 !his could be called "ith #arious arrays as follo"s5 /* first array bounds from -5 to +10 and 3 to 9 */ #e-lare array0 (D5C00* 6CE)float3 /* second array bounds from 1 to 16 and 1 to 16 */ #e-lare array4 (0A*0A) float3 -all -han'e;si'n(array0)3 -all -han'e;si'n(array4)3

$edit&8ocal

#ariables, recursion and reentrancy

' subprogram may find it useful to make use of a certain amount of scratch space< that is, memory used during the e)ecution of that subprogram to hold intermediate results 9ariables stored in this scratch space are termed local variables, and the scratch space is termed an activation record 'n acti#ation record typically has a return address that tells it "here to pass control back to "hen the subprogram finishes ' subprogram may ha#e any number and nature of call sites If recursion is supported, a subprogram may e#en call itself, causing its e)ecution to suspend "hile another nested e)ecution of the same subprogram occurs Recursion is a useful means to simplify some comple) algorithms, and breaking do"n comple) problems Recursi#e languages generally pro#ide a ne" copy of local #ariables on each call If the programmer desires the #alue of local #ariables to stay the same bet"een calls, they can be declared static in some languages, or global #alues or common areas can be used 7ere is an e)ample of recursi#e subroutine in >(>? ? to find Fibonacci numbers5 int fi!(int n) 1 if(nF=0) ret rn n3 ret rn fi!(nD0)+fi!(nD4)3 2 6arly languages like Fortran did not initially support recursion because #ariables "ere statically allocated, as "ell as the location for the return address +ost computers before the late %BCDs such as the P,P4J did not ha#e support for hard"are stack registers
$citation needed&

+odern languages after '8-=8 such as P8(% and > almost in#ariably use a stack, usually supported by most modern computer instruction sets to pro#ide a fresh acti#ation record for e#ery e)ecution of a subprogram !hat "ay, the nested e)ecution is free to modify its local #ariables "ithout concern for the effect on other suspended e)ecutions in progress 's nested calls accumulate, a call stack structure is formed, consisting of one acti#ation record for each suspended subprogram In fact, this stack structure is #irtually ubiquitous, and so acti#ation records are commonly termed stack frames Some languages such as Pascal and 'da also support nested subroutines, "hich are subroutines callable only "ithin the scopeof an outer (parent) subroutine Inner subroutines ha#e access to the local #ariables of the outer subroutine that called them !his is accomplished by storing e)tra conte)t information "ithin the acti#ation record, also termed a display If a subprogram can function properly e#en "hen called "hile another e)ecution is already in progress, that subprogram is said to be reentrant ' recursi#e subprogram must be reentrant Reentrant subprograms are also useful in multi4threadedsituations, since multiple threads can call the same subprogram "ithout fear of interfering "ith each other In the I:+ >I>Stransaction processing system, quasi reentrant "as a slightly less restricti#e, but similar, requirement for application programs that "ere shared by many threads

In a multi4threaded en#ironment, there is generally more than one stack 'n en#ironment that fully supports coroutines or laEy e#aluation may use data structures other than stacks to store their acti#ation records

$edit&=#erloading
In strongly typed languages, it is sometimes desirable to ha#e a number of functions "ith the same name, but operating on different types of data, or "ith different parameter profiles For e)ample, a square root function might be defined to operate on reals, comple) #alues or matrices !he algorithm to be used in each case is different, and the return result may be different :y "riting three separate functions "ith the same name, the programmer has the con#enience of not ha#ing to remember different names for each type of data Further if a subtype can be defined for the reals, to separate positi#e and negati#e reals, t"o functions can be "ritten for the reals, one to return a real "hen the parameter is positi#e, and another to return a comple) #alue "hen the parameter is negati#e In ob3ect4oriented programming, "hen a series of functions "ith the same name can accept different parameter profiles or parameters of different types, each of the functions is said to beo#erloaded 7ere is an e)ample of subroutine o#erloading in >??5 Gin-l #eFiostrea.> sin' na.espa-e st#3 #o !le area(#o !le h*#o !le H)1 ret rn h=H3 2 #o !le area(#o !le r)1 ret rn r=r=6.0<3 2 int .ain()1 #o !le re-tan'le;area=area(6*<)3 #o !le -ir-le;area=area(5)3 -o tFFre-tan'le;areaFFen#l3 -o tFF-ir-le;areaFFen#l3 ret rn 03 2 In this code there are t"o functions of same name but they ha#e different parameters 's another e)ample, a subroutine might construct an ob3ect that "ill accept directions, and trace its path to these points on screen !here are a plethora of parameters that could be passed in to the constructor (colour of the trace, starting ) and y co4ordinates, trace speed) If the programmer "anted the constructor to be able to accept only the color parameter, then he could call another constructor that accepts only color, "hich in turn calls the constructor "ith all the parameters passing in a set of default values for all the other parameters (H

and F "ould generally be centered on screen or placed at the origin, and the speed "ould be set to another #alue of the coder*s choosing)

$edit&>losures
!ain article" #losure (computer science) ' closure is a subprogram together "ith the #alues of some of its #ariables captured from the en#ironment in "hich it "as created >losures "ere a notable feature of the 8isp programming language, introduced by 1ohn +c>arthy ,epending on the implementation, closures can ser#e as a mechanism for side4effects

$edit&>on#entions
' "ide number of con#entions for the coding of subroutines ha#e been de#eloped Pertaining to their naming, many de#elopers ha#e adopted the approach that the name of a subroutine should be a#erb "hen it does a certain task, an ad3ecti#e "hen it makes some inquiry, and a noun "hen it is used to substitute #ariables Some programmers suggest that a subroutine should perform only one task, and if a subroutine does perform more than one task, it should be split up into more subroutines !hey argue that subroutines are key components in code maintenance, and their roles in the program must remain distinct Proponents of modular programming (modulariEing code) ad#ocate that each subroutine should ha#e minimal dependency on other pieces of code For e)ample, the use of global #ariables is generally deemed un"ise by ad#ocates for this perspecti#e, because it adds tight coupling bet"een the subroutine and these global #ariables If such coupling is not necessary, their ad#ice is to refactor subroutines to accept passed parameters instead 7o"e#er, increasing the number of parameters passed to subroutines can affect code readability

$edit&Return

codes

:esides its main or normal effect, a subroutine may need to inform the calling program about e$ceptional conditions that may ha#e occurred during its e)ecution In some languages and(or programming standards, this is often done through a return code, an integer #alue placed by the subroutine in some standard location, "hich encodes the normal and e)ceptional conditions In the I:+ System(/CD, "here a return code "as e)pected from the subroutine, the return #alue "as often designed to be a multiple of 0Mso that it could be used as a direct branch tableinde) into a branch table often located immediately after the call instruction to a#oid e)tra conditional tests, further impro#ing efficiency In the System(/CD assembly language, one "ould "rite, for e)ample5

B)I re'ister B 9)BIK B B Bran-h ta!le B

0<*SUB,9$00 9)BIK(05) %L B)N K,,%,

'o to s !ro tine* as ret rn /al e)

sin' re' 0< as sa/e

(sets re' 05 to 0*<*J

se ret rne# /al e in re' 05 to in#ex the ret rn -o#e =00 ret rn -o#e =0< ret rn -o#e =0J M%%N +n/ali# inp t Unexpe-te# -on#ition 2 2 2

!ran-h ta!le* !ran-hin' to the appropriate !ran-h instr.

$edit&=ptimiEation

of subroutine calls

!here is a significant runtime o#erhead in a calling a subroutine, including passing the arguments, branching to the subprogram, and branching back to the caller !he o#erhead often includes sa#ing and restoring certain processor registers, allocating and reclaiming call frame storage, etc In some languages, each subroutine calls also implies automatic testing of the subroutine*s return code, or the handling of e)ceptions that it may raise In ob3ect4oriented languages, a significant source of o#erhead is the intensi#ely used dynamic dispatch for method calls !here are some seemingly ob#ious optimiEations of procedure calls that cannot be applied if the procedures may ha#e side effects For e)ample, in the e)pression (f(x)D0)O(f(x)+0), the function f must be called t"ice, because the t"o calls may return different results +oreo#er, the #alue of x must be fetched again before the second call, since the first call may ha#e changed it ,etermining "hether a subprogram may ha#e a side effect is #ery difficult (indeed, undecidable) $citation needed& So, "hile those optimiEations are safe in purely functional programming languages, compilers of typical imperati#e programming usually ha#e to assume the "orst

$edit&%nlining
' method used to eliminate this o#erhead is inline e$pansion orinlining of the subprogram*s body at each call site (#ersus branching to the subroutine and back) ;ot only does this a#oid the call o#erhead, but it also allo"s the compiler to optimiEe the procedure*s body more effecti#ely by taking into account the conte)t and arguments at that call !he inserted body can be optimiEed by the compiler Inlining ho"e#er, "ill usually increase the code siEe, unless the program contains only one call to the subroutine, or the subroutine body is less code than the call o#erhead

$edit&See

also
Loo- up subroutine in Ai-tionary7 the &ree dictionary.

Function (mathematics) +ethod (computer programming) 6#aluation strategy +odular programming !ransclusion =perator o#erloading Functional programming >ommand4query separation >oroutines, subprograms that call each other as if both "ere the main programs 6#ent handler, a subprogram that is called in response to an input e#ent or interrupt

$edit&References
% & G S 6lection 'ssistance >ommission (.DDK) L,efinitions of Words "ith Special +eaningsL Voluntary Voting %ystem &uidelines Retrie#ed .D%/4D%4%0 . & Wilkes, + 9 < Wheeler, , 1 < -ill, S (%B2%) Preparation of Programs for an 'lectronic (igital #omputer 'ddison4Wesley / & ,ainith, 1ohn LLopen subroutine L ' ,ictionary of >omputing .DD0 L 'ncyclopedia)com Retrie#ed 1anuary %0, .D%/ 0 & ,onald 6 Nnuth *he +rt of #omputer Programming, Volume -" .undamental +lgorithms 'ddison4Wesley IS:; D4.D%4JBCJ/40 2 & = 41 ,ahl< 6 W ,i3kstra, > ' R 7oare (%BK.) %tructured Programming 'cademic Press IS:; D4%.4.DD22D4/ C K J & $%& & $.& & $/&

>ategories5

Source code

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