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

Introduction to C Programming
The University of Adelaide, School of Computer Science
CSI 3120, Implementing subprograms, page 1 Implementing subprograms The environment in block-structured languages The structure of the activation stack.
Procedures in more detail. CMPE12cGabriel Hugh Elkaim 2 Why use procedures? –Code reuse –More readable code –Less code Microprocessors (and assembly languages)
Apr. 12, 2000Systems Architecture I1 Systems Architecture I (CS ) Lecture 6: Branching and Procedures in MIPS* Jeremy R. Johnson Wed. Apr. 12, 2000.
The University of Adelaide, School of Computer Science
 Procedures (subroutines) allow the programmer to structure programs making them : › easier to understand and debug and › allowing code to be reused.
1 Storage Registers vs. memory Access to registers is much faster than access to memory Goal: store as much data as possible in registers Limitations/considerations:
1 Chapter 7: Runtime Environments. int * larger (int a, int b) { if (a > b) return &a; //wrong else return &b; //wrong } int * larger (int *a, int *b)
1 Function Calls Professor Jennifer Rexford COS 217 Reading: Chapter 4 of “Programming From the Ground Up” (available online from the course Web site)
Runtime Environments Source language issues Storage organization
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 3: Functions.
Run time vs. Compile time
Semantics of Calls and Returns
Functions and Program Structure Chapter 4. Introduction Functions break large computing tasks into smaller ones Appropriate functions hide details of.
Overview C programming Environment C Global Variables C Local Variables Memory Map for a C Function C Activation Records Example Compilation.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CS 201 Functions Debzani Deb.
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
Chapter 6: User-Defined Functions I
C Stack Frames / Pointer variables Stack: Local Variables Pass & Return values Frame Ptr linkage (R5) and PC linkage (R7) Pointer Variables: Defining &
Recursion and Implementation of Functions
Chapter 8 :: Subroutines and Control Abstraction
The C Language int i;main(){for(;i["]
Runtime Environments What is in the memory? Runtime Environment2 Outline Memory organization during program execution Static runtime environments.
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.
Programming Language Principles Lecture 24 Prepared by Manuel E. Bermúdez, Ph.D. Associate Professor University of Florida Subroutines.
Compiler Construction
Chapter 6: User-Defined Functions
Lecture 18: 11/5/2002CS170 Fall CS170 Computer Organization and Architecture I Ayman Abdel-Hamid Department of Computer Science Old Dominion University.
Activation Records (in Tiger) CS 471 October 24, 2007.
CSC3315 (Spring 2008)1 CSC 3315 Subprograms Hamid Harroud School of Science and Engineering, Akhawayn University
Chapter 12 – Types, Operators, Expressions First chimp in space.
Procedure Basics Computer Organization I 1 October 2009 © McQuain, Feng & Ribbens Procedure Support From previous study of high-level languages,
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Computer programming Outline Functions [chap 8 – Kochan] –Defining a Function –Arguments and Local Variables Automatic Local.
CCSA 221 Programming in C CHAPTER 8 – PART 1 WORKING WITH FUNCTIONS 1.
CSC 8505 Compiler Construction Runtime Environments.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used.
Functions. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 9-2 JSR Instruction Jumps to a location (like.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
4-1 Embedded Systems C Programming Language Review and Dissection II Lecture 4.
Chapter 3: User-Defined Functions I
RUNTIME ENVIRONMENT AND VARIABLE BINDINGS How to manage local variables.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
Functions and Program Structure Chapter 4. Introduction Functions break large computing tasks into smaller ones Appropriate functions hide details of.
LECTURE 19 Subroutines and Parameter Passing. ABSTRACTION Recall: Abstraction is the process by which we can hide larger or more complex code fragments.
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.
Run-Time Environments Chapter 7
Computer Science 210 Computer Organization
Chapter 6: User-Defined Functions I
Procedures (Functions)
Chapter 14 Functions.
User-Defined Functions
Chapter 9 :: Subroutines and Control Abstraction
Chapter 14 Functions.
Chapter 14 Functions.
Activation records Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section
UNIT V Run Time Environments.
Runtime Environments What is in the memory?.
Activation records Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section
Chapter 14 Functions.
Chapter 14 Functions.
Presentation transcript:

Chapter 14 Functions

Variables and Operators Topics to Cover… Functions C Functions Function Examples Function Notes main Function Activation Records Run-time Stack Function Calls BYU CS/ECEn 124 Variables and Operators

Variables and Operators Functions Functions Smaller, simpler, subcomponent of program Provides abstraction hide low-level details give high-level structure to program, easier to understand overall program flow enables separable, independent development Decomposition Functions break large computing tasks into smaller ones. Functions enlarge the set of elementary building blocks. In other languages, called procedures, methods, subroutines, ... BYU CS/ECEn 124 Variables and Operators

Example of High-Level Structure Functions Example of High-Level Structure int main() { SetupBoard(); /* place pieces on board */ DetermineSides(); /* choose black/white */ /* Play game */ do { WhitesTurn(); BlacksTurn(); } while (NoOutcomeYet()); } Structure of program is evident, even without knowing implementation. BYU CS/ECEn 124 Variables and Operators

Variables and Operators Functions The Power of Functions Decomposition Functions break large computing tasks into smaller ones. Functions enlarge the set of elementary building blocks. Abstraction Separate the “function” of a component from the details of how it is accomplished. The component can be used as a building block while hiding the details in the function. BYU CS/ECEn 124 Variables and Operators

Variables and Operators Functions Functions in C Functions have been in all programming languages since the very early days of computing. Support for functions is provided directly in all instruction set architectures. C is heavily oriented around functions. A C program is organized as a collection of functions. Every C statement belongs to a function All C programs start and finish execution in the function main Functions may call other functions which, in turn, call more functions. BYU CS/ECEn 124 Variables and Operators

Variables and Operators C Functions Parts of a C Function The Declaration: Informs the compiler about the function. The Definition: The function body contained inside braces {...}. The Return Value: Calculated by the function, and returned by a return statement in the body. The Call: Arguments (actual parameters) from the caller are transmitted to the function parameters (formal parameters). BYU CS/ECEn 124 Variables and Operators

Variables and Operators C Functions Parts of a C Function The Declaration: type name(type, type, ... ); Informs the compiler about the function Only argument types needed Ends in a semi-colon The function prototype declares: The function name The type of the output value returned by the function (void = nothing returned) The types of input arguments that the function accepts as input BYU CS/ECEn 124 Variables and Operators

Variables and Operators C Functions Parts of a C Function The Definition: type name(type param, type param,...) { body } The first line matches type in the declaration (but without the semicolon) The list of input arguments (formal parameters) by type and name The function body contained inside braces {...} BYU CS/ECEn 124 Variables and Operators

Variables and Operators C Functions Parts of a C Function The Return Value: return expression; Returned by a return statement in the body Must match declaration return type The Call: name(expression, expression, ... ) Arguments (actual parameters) from the caller are transmitted to the function parameters (formal parameters) Function definitions and function calls must having matching prototypes. BYU CS/ECEn 124 Variables and Operators

Variables and Operators Function Examples Example #1 #include <stdio.h> int addNumbers(int, int); int main() { printf("\nResult is: %d", addNumbers(4, 5)); } int addNumbers(int x, int y) return (x+y); function prototype (declaration) arguments formal parameters function definition BYU CS/ECEn 124 Variables and Operators

Variables and Operators Function Examples Example #2 #include <stdio.h> void PrintBanner(); /* function declaration */ int main() { PrintBanner(); /* function call */ printf("\nA simple C program."); PrintBanner(); /* function call */ } void PrintBanner() /* function definition */ { printf("\n=================================="); } /* no return value needed */ BYU CS/ECEn 124 Variables and Operators

Variables and Operators Function Examples Example #3 #include <stdio.h> int Factorial(int n); // function declaration int main() { int number, answer; ... answer = Factorial(number); // function call ... } int Factorial(int n) // function definition { int i; int result = 1; for(i=1; i<=n; i++) result = result * i; return result; // return value to caller } BYU CS/ECEn 124 Variables and Operators

Variables and Operators Function Notes Function Notes Minimal do-nothing function void dummy( ) {} Default return type is integer three( ) { return 3; } int three( ) { return 3; } Function definitions cannot nest Function arguments are local to the function Function arguments are passed “by value” Temporary (private) variables rather than the originals Value could be a reference (such as with an array) Call by value is an asset, not a liability These are the same BYU CS/ECEn 124 Variables and Operators

Variables and Operators Function Notes Function Notes The scope of a name (variable or function) is the part of the program within which the name can be used. A function prototype “extends” the scope of a function and helps the compiler check function call syntax. with prototype ... int xyz(int, int); ... scope of xyz without prototype int xyz(int x, int y) { ... } ... /* end of file */ BYU CS/ECEn 124 Variables and Operators

Variables and Operators main Function The main Function Must be present in every program Is “called” by the operating system when program is run Returning from main exits the program Is pre-declared as: int main (int argc, char *argv[]); The definition doesn’t have to match. int main() { ... } main() { ... } The return statement can be omitted. Don’t worry about what this means. These are OK BYU CS/ECEn 124 Variables and Operators

Implementing Functions in C Activation Records Implementing Functions in C Functions are the C equivalent of subroutine in assembly language. Function calls involve three basic steps Parameters from caller are passed to the callee. Control is passed to callee. Callee does the task Return value is passed back to caller. Control returns to the caller. Functions must be caller-independent, i.e. callable from any function. BYU CS/ECEn 124 Variables and Operators

Variables and Operators Activation Records Activation Records When a function is called, it needs to be activated, that is, local variables must be given locations in memory. An activation record for a function is a template of the relative positions of its local variables in memory. A frame is a local data storage area allocated on the stack each time a function is called for the activation record. Frame variables are for temporary storage and are lost when the function returns. The stack pointer is used for the frame pointer. Data is stored and retrieved via indexed stack instructions. mov.w r12,0(sp) ; save parameter 1 mov.w 0(sp),r12 ; return value BYU CS/ECEn 124 Variables and Operators

Run-time Stack Operation Program starts main calls A A calls B Memory Memory SP func B SP func A func A SP main main main BYU CS/ECEn 124 Variables and Operators

Runtime Stack Operation B returns to A A returns to main Memory Memory SP func A SP main main BYU CS/ECEn 124 Variables and Operators

Stack Frames / Parameter Passing Activation Records Stack Frames / Parameter Passing Each function call creates a new stack frame. The parameters of a called function are passed to a function in a right to left order. Up to four left most parameters are passed in registers unless they are defined as a struct or union type, in which case they are also passed on the stack. The remaining parameters are always passed on the stack. BYU CS/ECEn 124 Variables and Operators

Stack Frames / Parameter Passing Activation Records Stack Frames / Parameter Passing Each function call creates a new stack frame. High Address Stack Parameters (When more than 4) Frame or Activation Record Return Address Saved Registers (if any) Local Variables Stack Pointer (SP) Low Address BYU CS/ECEn 124 Variables and Operators

Activation Record (Frame) Activation Records Activation Record (Frame) int func(int a, int b) { int x, y, z; … return y; } Memory Return Address Bookkeeping Info z y Symbol Table x Local variables b Name Type Offset Scope SP  a a int 0(SP) func b int 2(SP) func x int 4(SP) func y int 6(SP) func z int 8(SP) func BYU CS/ECEn 124 Variables and Operators

Stack Frames / Parameter Passing Run-time Stack Stack Frames / Parameter Passing main: 0x8762: 8221 SUB.W #4,SP 0x8764: 40B1 0032 0000 MOV.W #0x0032,0x0000(SP) 0x876a: 40B1 003C 0002 MOV.W #0x003c,0x0002(SP) 0x8770: 403C 000A MOV.W #0x000a,R12 0x8774: 403D 0014 MOV.W #0x0014,R13 0x8778: 403E 001E MOV.W #0x001e,R14 0x877c: 403F 0028 MOV.W #0x0028,R15 0x8780: 12B0 853C CALL #func 0x8784: 430C CLR.W R12 0x8786: 5221 ADD.W #4,SP 0x8788: 4130 RET func: 0x853c: 8031 000E SUB.W #0x000e,SP 0x8540: 4F81 0006 MOV.W R15,0x0006(SP) 0x8544: 4E81 0004 MOV.W R14,0x0004(SP) 0x8548: 4D81 0002 MOV.W R13,0x0002(SP) 0x854c: 4C81 0000 MOV.W R12,0x0000(SP) 0x8550: 4391 0008 MOV.W #1,0x0008(SP) 0x8554: 43A1 000A MOV.W #2,0x000a(SP) 0x8558: 40B1 0003 000C MOV.W #0x0003,0x000c(SP) 0x855e: 411C 0002 MOV.W 0x0002(SP),R12 0x8562: 512C ADD.W @SP,R12 0x8564: 511C 0004 ADD.W 0x0004(SP),R12 0x8568: 511C 0006 ADD.W 0x0006(SP),R12 0x856c: 511C 0010 ADD.W 0x0010(SP),R12 0x8570: 511C 0012 ADD.W 0x0012(SP),R12 0x8574: 511C 0008 ADD.W 0x0008(SP),R12 0x8578: 511C 000A ADD.W 0x000a(SP),R12 0x857c: 511C 000C ADD.W 0x000c(SP),R12 0x8580: 5031 000E ADD.W #0x000e,SP 0x8584: 4130 RET Example: int func(a, b, c, d, e, f) { int x, y, z; x = 1; y = 2; z = 3; return a+b+c+d+e+f+x+y+z; } int main() func(10, 20, 30, 40, 50, 60); return 0; f 60 0x0012(SP) e 50 0x0010(SP) Return adr z 3 0x000c(SP) y 2 0x000a(SP) x 1 0x0008(SP) d 40 0x0006(SP) c 30 0x0004(SP) b 20 0x0002(SP) a 10 0x0000(SP) SP  BYU CS/ECEn 124 Variables and Operators

Variables and Operators Function Calls Function Calls Caller If more than 4 arguments, push function arguments on stack (right-to-left) Put 1st argument in R12, 2nd argument in R13,… Transfer control to function with call instruction Callee Create activation record on the stack Save arguments in activation record Save any callee-saved registers that are altered in activation record. BYU CS/ECEn 124 Variables and Operators

Variables and Operators Function Calls The Return Callee Put return value in R12 Restore any saved registers Pop activation record Return control to caller (RET = mov.w @sp+,pc) Caller Return value is in R12 BYU CS/ECEn 124 Variables and Operators

Activation Record (Frame) Function Calls Activation Record (Frame) Memory int main() { int n; int m; … m = func(n, 10); } int func(int a, int b) int x, y, z; return y; Return Address Activation Record for main m Local variables n Return Address z Activation Record for func y Local variables x b SP  a BYU CS/ECEn 124 Variables and Operators

Variables and Operators BYU CS/ECEn 124 Variables and Operators