Chapter 14 Functions.

Slides:



Advertisements
Similar presentations
Chapter 14 Functions. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Function Smaller, simpler, subcomponent.
Advertisements

Run-time Environment for a Program different logical parts of a program during execution stack – automatically allocated variables (local variables, subdivided.
Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
Ch. 8 Functions.
 Procedures (subroutines) allow the programmer to structure programs making them : › easier to understand and debug and › allowing code to be reused.
CSS 372 Lecture 1 Course Overview: CSS 372 Web page Syllabus Lab Ettiquette Lab Report Format Review of CSS 371: Simple Computer Architecture Traps Interrupts.
Chapter 17 Recursion. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Mathematical Definition: RunningSum(1)
Chapter 11-14, Appendix D C Programs Higher Level languages Compilers C programming Converting C to Machine Code C Compiler for LC-3 Please return breadboards.
1 Introduction to “C” Control Loops and Functions Patt and Patel Ch. 13 & 14.
Run-Time Storage Organization
Run time vs. Compile time
Semantics of Calls and Returns
Overview C programming Environment C Global Variables C Local Variables Memory Map for a C Function C Activation Records Example Compilation.
CS 201 Functions Debzani Deb.
C Stack Frames / Pointer variables Stack: Local Variables Pass & Return values Frame Ptr linkage (R5) and PC linkage (R7) Pointer Variables: Defining &
Chapter 8 :: Subroutines and Control Abstraction
ISBN Chapter 10 Implementing Subprograms.
Chapter 14 Functions. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Function Smaller, simpler, subcomponent.
CMPE13Cyrus Bazeghi Chapter 14 Functions in C. CMPE13 2 Functions Smaller, simpler, subcomponents of programs Provide abstraction –hide low-level details.
Functions & Activation Records Recursion
Runtime Environments Compiler Construction Chapter 7.
Chapter 17 Pointers and Arrays. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Pointers and Arrays.
Compiler Construction
Chapter 14 Functions.
1 Control Abstraction (Section ) CSCI 431 Programming Languages Fall 2003 A compilation of material developed by Felix Hernandez-Campos and Michael.
142 F -1 Functions chapter 3 of the text int main(void) { double x,y,z; … x = cube(y/3.0); … printf(“%f cubed is %f”,x,cube(x)); … return 0; } double cube(double.
CSC 8505 Compiler Construction Runtime Environments.
Functions. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 9-2 JSR Instruction Jumps to a location (like.
Chapter 14 Functions. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Declarations (aka prototype) int.
4-1 Embedded Systems C Programming Language Review and Dissection II Lecture 4.
RUNTIME ENVIRONMENT AND VARIABLE BINDINGS How to manage local variables.
LECTURE 19 Subroutines and Parameter Passing. ABSTRACTION Recall: Abstraction is the process by which we can hide larger or more complex code fragments.
Function Calls in Assembly MIPS R3000 Language (extensive use of stack) Updated 7/11/2013.
Chapter 14 Functions.
Storage Classes There are three places in memory where data may be placed: In Data section declared with .data in assembly language in C - Static) On the.
Chapter 10 : Implementing Subprograms
Run-Time Environments Chapter 7
Implementing Subprograms Chapter 10
Computer Science 210 Computer Organization
Chapter 17 Recursion.
Implementing Subprograms
Chapter 12 Variables and Operators
Chapter 14 Functions.
Programmazione I a.a. 2017/2018.
User-Defined Functions
Chapter 9 :: Subroutines and Control Abstraction
Chapter 16 Pointers and Arrays
Chapter 14 Functions.
More C Stack Frames / Pointer variables
Chapter 17 Recursion.
Chap. 8 :: Subroutines and Control Abstraction
Chap. 8 :: Subroutines and Control Abstraction
Procedures – Overview Lecture 19 Mon, Mar 28, 2005.
CSC 533: Programming Languages Spring 2015
The University of Adelaide, School of Computer Science
Understanding Program Address Space
Chapter 16 Pointers and Arrays
Chapter 17 Recursion.
Runtime Environments What is in the memory?.
10/6: Lecture Topics C Brainteaser More on Procedure Call
Where is all the knowledge we lost with information? T. S. Eliot
CSC 533: Programming Languages Spring 2018
CSC 533: Programming Languages Spring 2019
Chapter 14 Functions.
Return-to-libc Attacks
Chapter 16 Pointers and Arrays
Chapter 17 Recursion.
Chapter 14 Functions.
Implementing Functions: Overview
Presentation transcript:

Chapter 14 Functions

Function Smaller, simpler, subcomponent of program Provides abstraction hides low-level details gives high-level structure to program and makes it easier to understand overall program flow enables separable, independent development C functions zero or multiple arguments passed in single result returned (optional) return value is always a particular type In other languages, called procedures, subroutines, ...

3. use return value in expression Functions in C (1) Declaration (also called prototype) int Factorial(int n); (2) Function call -- used in expression a = x + Factorial(f + g); type of return value name of function types of all arguments 1. evaluate arguments 2, execute function 3. use return value in expression

gives control back to calling function and returns value Functions in C (3) Function Definition State type, name, types of arguments must match function declaration give name to each argument (doesn't have to match declaration but why not?) int Factorial(int n) { int i; int result = 1; for (i = 1; i <= n; i++) result = reslt * i; return result; } gives control back to calling function and returns value

Why Declaration? Since function definition also includes return and argument types, why is declaration needed? can use a function before its 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 only compile separately, link together to make executable

Another Example declaration function call (invocation) definition double 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; declaration function call (invocation) definition

A Complete Example (1) #include <stdio.h> /* Function declarations */ double AreaOfCircle(double radius); int main() { double outer; /* Outer radius */ double inner; /* Inner radius */ double areaOfRing; /* Area of ring */ printf("Enter outer radius: "); scanf("%lf", &outer); printf("Enter inner radius: "); scanf("%lf", &inner); areaOfRing = AreaOfCircle(outer) - AreaOfCircle(inner); printf("The area of the ring is %f\n", areaOfRing); } /* Calculate area of circle given a radius */ double AreaOfCircle(double radius) double pi = 3.14159265; return pi * radius * radius;

A Complete Example (2-1) #include <stdio.h> /* Function declaration */ char ToUpper(char inchar); /* Function main: */ /* Prompt for a line of text, Read one character, */ /* convert to uppercase, print it out, then get another */ int main() { char echo = 'A'; /* Initialize input character */ char upcase; /* Converted character */ while (echo != '\n') { scanf("%c", &echo); upcase = ToUpper(echo); printf("%c", upcase); }

A Complete Example (2-2) /* Function ToUpper: */ /* If the parameter is lower case return */ /* its uppercase ASCII value */ char ToUpper(char inchar) { char outchar; if ('a' <= inchar && inchar <= 'z') outchar = inchar - ('a' - 'A'); else outchar = inchar; return outchar; }

A Complete Example (3) #include <stdio.h> int Squared(int x); int main() { int sideA; int sideB; int sideC; int maxC; printf("Enter the maximum length of hypotenuse: "); scanf("%d", &maxC); for (sideC = 1; sideC <= maxC; sideC++) { for (sideB = 1; sideB <= maxC; sideB++) { for (sideA = 1; sideA <= maxC; sideA++) { if (Squared(sideC) == Squared(sideA) + Squared(sideB)) printf("%d %d %d\n", sideA, sideB, sideC); } /* Calculate the square of a number */ int Squared(int x) return x * x;

Implementing Functions: Overview Activation record information about each function, including arguments, return value, local variables stored on run-time stack Calling function (caller) Called function (callee) - copy values into arguments - call function - allocate local variables - execute code - put return value in activation record - deallocate local variables - return - get result from stack

Run-Time Stack Recall that local variables are stored on the run-time stack in an activation record Frame pointer (R5) points to the beginning of a region of activation record that stores local variables for the current function When 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.

Example int main() { int a; int b; ... b = Watt(a); b = Volta(a, b); } int Watt(int a) { int w; ... w = Volta(w,10); ... return w; } int Volta(int q, int r) { int k; int m; ... return k; }

Run-Time Stack Memory R6 R5 R6 R5 R6 R5 Volta Watt Watt main main main When execution starts When Watt executes When Volta executes

Run-Time Stack Memory Memory R6 R6 R5 R5 R6 R5 Watt Volta main main When Volta completes When Watt completes When Volta executes

Activation Record int FName(int a, int b) { int w, x, y; . . . return y; } R6 y x w dynamic link return address return value a b locals R5 bookkeeping args Name Type Offset Scope a b w x y int 4 5 -1 -2 FName

Activation Record Bookkeeping Return value space for value returned by function allocated even if function does not return a value Return address save pointer to next instruction in calling function convenient location to store R7 in case another function (JSR) is called Dynamic link caller’s frame pointer used to pop this activation record from stack

Example Function Call int Volta(int q, int r) { int k; int m; ... return k; } int Watt(int a) { int w; ... w = Volta(w,10); ... return w; }

Calling the Function w = Volta(w, 10); 25 10 q r w dyn link ret addr ret val a w = Volta(w, 10); ; push second arg AND R0, R0, #0 ADD R0, R0, #10 ADD R6, R6, #-1 STR R0, R6, #0 ; push first argument LDR R0, R5, #0 ADD R6, R6, #-1 STR R0, R6, #0 ; call subroutine JSR Volta new R6 R6 R5 xFD00 Note: Caller needs to know number and type of arguments, doesn't know about callee’s local variables.

Starting the Callee Function xFCFB x3100 25 10 m k dyn link ret addr ret val q r w a ; leave space for return value ADD R6, R6, #-1 ; push return address ADD R6, R6, #-1 STR R7, R6, #0 ; push dyn link (caller’s frame ptr) ADD R6, R6, #-1 STR R5, R6, #0 ; set new frame pointer ADD R5, R6, #-1 ; allocate space for locals ADD R6, R6, #-2 new R6 new R5 R6 R5 xFD00

Ending the Callee Function -43 217 xFCFB x3100 25 10 m k dyn link ret addr ret val q r w a return k; ; copy k into return value LDR R0, R5, #0 STR R0, R5, #3 ; pop local variables ADD R6, R5, #1 ; pop dynamic link (into R5) LDR R5, R6, #0 ADD R6, R6, #1 ; pop return addr (into R7) LDR R7, R6, #0 ADD R6, R6, #1 ; return control to caller RET R6 R5 new R6 new R5 xFD00

Resuming the Caller Function 217 25 10 ret val q r w dyn link ret addr a w = Volta(w,10); JSR Volta ; load return value (top of stack) LDR R0, R6, #0 ; perform assignment STR R0, R5, #0 ; pop return value ADD R6, R6, #1 ; pop arguments ADD R6, R6, #2 R6 new R6 R5 xFD00

Summary of LC-3 Function Call Implementation Caller 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 computation…

꼭 기억해야 할 것 Function Activation Record on the stack contains -43 217 Declaration Invocation Definition Activation Record on the stack contains Argument values (allocated & set up & deallocated by caller) return value (allocated & set up by callee and used & deallocated by caller) return address (allocated & set up & deallocated by callee) dynamic link – caller’s R5 (allocated & set up & deallocated by callee) local variables - more precisely automatic variables (allocated & set up and deallocated by callee) -43 217 xFCFB x3100 25 10 m k dyn link ret addr ret val q r w a