Tài liệu Bài giảng Chapter 14 Functions: Chapter 14FunctionsFunctionSmaller, simpler, subcomponent of programProvides abstractionhide low-level detailsgive high-level structure to program,easier to understand overall program flowenables separable, independent developmentC functionszero or multiple arguments passed insingle result returned (optional)return value is always a particular typeIn other languages, called procedures, subroutines, ...2Example of High-Level Structuremain(){ SetupBoard(); /* place pieces on board */ DetermineSides(); /* choose black/white */ /* Play game */ do { WhitesTurn(); BlacksTurn(); } while (NoOutcomeYet());}Structure of programis evident, even withoutknowing implementation.3Functions in CDeclaration (also called prototype) int Factorial(int n);Function call -- used in expression a = x + Factorial(f + g);type ofreturn valuename offunctiontypes of allarguments1. evaluate arguments2, execute function3. use return value in expression4Function DefinitionState type, name, types of a...
18 trang |
Chia sẻ: honghanh66 | Lượt xem: 882 | Lượt tải: 0
Bạn đang xem nội dung tài liệu Bài giảng Chapter 14 Functions, để tải tài liệu về máy bạn click vào nút DOWNLOAD ở trên
Chapter 14FunctionsFunctionSmaller, simpler, subcomponent of programProvides abstractionhide low-level detailsgive high-level structure to program,easier to understand overall program flowenables separable, independent developmentC functionszero or multiple arguments passed insingle result returned (optional)return value is always a particular typeIn other languages, called procedures, subroutines, ...2Example of High-Level Structuremain(){ SetupBoard(); /* place pieces on board */ DetermineSides(); /* choose black/white */ /* Play game */ do { WhitesTurn(); BlacksTurn(); } while (NoOutcomeYet());}Structure of programis evident, even withoutknowing implementation.3Functions in CDeclaration (also called prototype) int Factorial(int n);Function call -- used in expression a = x + Factorial(f + g);type ofreturn valuename offunctiontypes of allarguments1. evaluate arguments2, execute function3. use return value in expression4Function DefinitionState type, name, types of argumentsmust match function declarationgive name to each argument (doesn't have to match declaration)int Factorial(int n){ int i; int result = 1; for (i = 1; i <= n; i++) result *= i; return result;}gives control back tocalling function and returns value5Why Declaration?Since function definition also includesreturn and argument types, why is declaration needed? Use might be seen before definition. Compiler needs to know return and arg types and number of arguments. Definition might be in a different file, written by a different programmer.include a "header" file with function declarations onlycompile separately, link together to make executable6Exampledouble ValueInDollars(double amount, double rate);main(){ ... dollars = ValueInDollars(francs, DOLLARS_PER_FRANC); printf("%f francs equals %f dollars.\n", francs, dollars); ...}double ValueInDollars(double amount, double rate){ return amount * rate;}declarationfunction call (invocation)definition7Implementing Functions: OverviewActivation recordinformation about each function,including arguments and local variablesstored on run-time stackCalling functionpush new activation recordcopy values into argumentscall functionget result from stackCalled functionexecute codeput result in activation recordpop activation record from stackreturn8Run-Time StackRecall that local variables are storedon the run-time stack in an activation recordFrame pointer (R5) points to the beginning of aregion of activation record that stores local variables forthe current functionWhen a new function is called, its activation record is pushed on the stack; when it returns, its activation record is popped off of the stack.9Run-Time StackmainMemoryR6WattMemoryR6mainMemorymainBefore callDuring callAfter callR5R5R6R510Activation Recordint NoName(int a, int b){ int w, x, y; . . . return y;}NameTypeOffsetScopeabwxyintintintintint450-1-2NoNameNoNameNoNameNoNameNoNameyxwdynamic linkreturn addressreturn valueabbookkeepinglocalsargsR511Activation Record BookkeepingReturn valuespace for value returned by functionallocated even if function does not return a valueReturn addresssave pointer to next instruction in calling functionconvenient location to store R7 in case another function (JSR)is calledDynamic linkcaller’s frame pointerused to pop this activation record from stack12Example Function Callint Volta(int q, int r) { int k; int m; ... return k;}int Watt(int a){ int w; ... w = Volta(w,10); ... return w;}13Calling the Functionw = Volta(w, 10);; push second argAND R0, R0, #0ADD R0, R0, #10ADD R6, R6, #-1STR R0, R6, #0; push first argumentLDR R0, R5, #0ADD R6, R6, #-1STR R0, R6, #0; call subroutineJSR Voltaqrwdyn linkret addrret vala25 1025xFD00new R6Note: Caller needs to know number and type of arguments,doesn't know about local variables.R5R614Starting the Callee Function; leave space for return valueADD R6, R6, #-1; push return addressADD R6, R6, #-1STR R7, R6, #0; push dyn link (caller’s frame ptr)ADD R6, R6, #-1STR R5, R6, #0; set new frame pointerADD R5, R6, #-1; allocate space for localsADD R6, R6, #-2mkdyn linkret addrret valqrwdyn linkret addrret valaxFCFBx310025 1025xFD00new R6new R5R6R515Ending the Callee Functionreturn k;; copy k into return valueLDR R0, R5, #0STR R0, R5, #3; pop local variablesADD R6, R5, #1; pop dynamic link (into R5)LDR R5, R6, #0ADD R6, R6, #1; pop return addr (into R7)LDR R7, R6, #0ADD R6, R6, #1; return control to callerRETmkdyn linkret addrret valqrwdyn linkret addrret vala-43217xFCFBx310021725 1025xFD00R6R5 new R6new R516Resuming the Caller Functionw = Volta(w,10);JSR Volta; load return value (top of stack)LDR R0, R6, #0; perform assignmentSTR R0, R5, #0; pop return valueADD R6, R6, #1; pop argumentsADD R6, R6, #2ret valqrwdyn linkret addrret vala21725 10217xFD00R6R5new R617Summary of LC-3 Function Call ImplementationCaller pushes arguments (last to first).Caller invokes subroutine (JSR).Callee allocates return value, pushes R7 and R5.Callee allocates space for local variables.Callee executes function code.Callee stores result into return value slot.Callee pops local vars, pops R5, pops R7.Callee returns (JMP R7).Caller loads return value and pops arguments.Caller resumes computation18
Các file đính kèm theo tài liệu này:
- pattpatelch14_4256.ppt