Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.

Slides:



Advertisements
Similar presentations
Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these.
Advertisements

Introduction to C Programming
Scope and Lifespan of Identifiers. Every function has a scope What does that mean? That means that every identifier that is created in a function (that’s.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Chapter 6: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Functions l Control structures l every C++ program must have a function called main l program execution.
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.
Chapter 6: User-Defined Functions I
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 6: Functions.
Chapter 7 Functions.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
1 Chapter 9 Scope, Lifetime, and More on Functions.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
1 Programming in C++ Dale/Weems/Headington Chapter 7 Functions.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
1 Functions every C++ program must have a function called main program execution always begins with function main any other functions are subprograms and.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
CPS120: Introduction to Computer Science Functions.
Functions. Let’s look at the 2 programs of evaluating: y=2^3+2^5+2^6; #include using namespace std; int main() { int y=0; int partResult=1; for (int i=1;
CPS120: Introduction to Computer Science Lecture 14 Functions.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 6 User-Defined Functions I. Objectives Standard (predefined) functions What are they, and How to use them User-Defined Functions Value returning.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
Chapter 7 Functions CS185/09 - Introduction to Programming Caldwell College.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
1 Scope Lifetime Functions (the Sequel) Chapter 8.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Chapter 9: Value-Returning Functions
User-Written Functions
Chapter 7: User-Defined Functions II
Completing the Problem-Solving Process
Programmazione I a.a. 2017/2018.
User-Defined Functions
Functions Inputs Output
User Defined Functions
Chapter 4 void Functions
Functions.
Chapter 6: User-Defined Functions I
Chapter 8 Functions.
Presentation transcript:

Functions in C++ Top Down Design with Functions

Top-down Design Big picture first broken down into smaller pieces

Can you tell what this is doing? int main () { rad = get_a_number(); display_input (rad); pie_area = find_area (rad); pie_cost = calccost (pie_area); draw_pie (rad, pie_cost); return 0; }

Why use functions? easier for programmers to work together put details off while looking at big picture easier to reuse code easier testing and debugging

Suppose you had some code that looked like this: side2 = pow(a, 2) + pow (b, 2); side4 = pow(c, 2) + pow (side2, 2); side7 = pow(b, 2) + pow (side4, 2); side3 = pow(5.3, 2) + pow (side2, 2); cout << pow (19.2, 2) + pow(angle3, 2) + angle9; why not abstract that expression and only have to write it once?

Function definition example //definition float myfun (float one, float two) // assumes //cmath has been included { return pow(one, 2) + pow (two, 2); } could you name the parameters?

Function call examples: // the code before becomes side2 = myfun (a, b); side4 = myfun (c, side2); side7 = myfun (b, side4); side3 = myfun (5.3, side2); cout << myfun (19.2, angle3) + angle9; could you name the arguments?

Function prototype example: float myfun (float one, float two); // assumes cmath has been included

Value-returning Function Syntax The Definition has header "return type" "name" ( parameter list ) has body - must be between braces body must have return x; where x is a constant or variable or expression location - anywhere in file but NOT nested in another function's body!

Value-returning Function Syntax The function call is an expression using "name ( argument list)" since the call is an expression, it must be part of a larger statement:  output  assignment statement (RHS)  if statement  while statement location of a call - wherever needed in code

Value-returning Function Syntax The Prototype just like header except ends with semicolon "float funA (int a, float b);" location near top of file prototypes go OUTSIDE of any function definitions! (not inside a function) parameter names are optional but a good idea! "int myfun (int, int, int);" is mysterious!

Value-returning Function Semantics A function is a control structure so how does it change the order of execution? Assume execution is happening at the statement below: x = myfun (5.0, angle3) * 17.2; steps that happen are described on next two slides

Value-returning Function Semantics x = myfun (5.0, angle3) * 17.2; 1. The right hand side of assignment statement must be evaluated 2. In order to do that, function call must be evaluated before the multiplication 3. Execution of this statement is paused 4. Arguments are copied into other memory locations for parameters  5.0 to one, angle3 to two 5. Any local variables declared are given space

Value-returning Function Semantics x = myfun (5.0, angle3) * 17.2; 6. Execution continues with the body of the function definition. The calculation takes place (including calls to pow) until one value results 7. The return value is prepared by placing in special memory location for ret value 8. Local variables and the copies made for the parameters are destroyed in memory

Value-returning Function Semantics x = myfun (5.0, angle3) * 17.2; 9. Execution picks up at the statement that was paused in step 3 and finishes the assignment statement

Some important points about function call semantics Arguments and parameters are matched up by the compiler: as to type - corresponding args and parms must match or be able to be converted as to quantity - must have same number of args and parms if these matchings don't happen correctly, you get a syntax error

Some important points about function call semantics Note that NAMES of arguments and parameters do NOT have to match! Just because a function is defined in a program, does not mean that it WILL always be executed - if it is not called by some statement it will not be done Arguments are in function calls, Parameters are in function definitions or prototypes

Classified by Location Always appear in a function call within the calling block Always appear in the function heading, or function prototype Arguments Parameters

Arguments / Parameters They are the interface between the function and the "outside world" matching is done by position - first to first, second to second, etc. careful about using "input" and "output" in referring to parameters - NOT from the keyboard and to the screen!

What is "an overloaded function"? You can have more than one function with the same name as long as the parameter list is different for each The compiler figures out which one you mean by the arguments you send If it can't distinguish which one you mean, then you get an error Usually an error message with this phrase in it means that you got the argument list wrong. Check types and number of arguments to see if they match parms

Value-Returning Functions #include int Square(int n); // Prototypes int Cube(int n); using namespace std; int main() { cout << “The square of 27 is “ << Square(27) << endl; cout << “The cube of 27 is “ << Cube(27) << endl; return 0; } function calls 21

Rest of Program int Square(int n)// Header and body { return n * n; } int Cube(int n)// Header and body { return n * n * n; }

Void function semantics Simpler than value-returning but similar 1. call is from a stand-alone statement 2. calling function paused at this point 3. arguments are copied to parameters 4. matching process takes place 5. control transfers to code of function definition

Void function semantics (cont’d) 6. if any local variables declared, they get space 7. code of function body executed 8. when end of body or a “return;” statement encountered, prepare to return  Destroy locals and copies of arguments 9. Return control to statement AFTER call

Scope "Where is this identifier known?" Parameters  from header line of function to right closing brace Local variables  from line of declaration inside function definition to right closing brace Global variables  from line of declaration to end of FILE - includes all functions following the declaration

Scope continued Local variables  created every time the function runs  initializations done every time they are created  destroyed when the function returns control

Scope continued Parameters  name is known from header line until end of function body  NAME does NOT have to match argument NAME  if passed by value, gets memory allocated and copy of argument made  if passed by reference, gets matched with space occupied by argument

Scope continued Global variables  declared outside of any function at all  known from point of declaration in file to end of FILE  allocated space at start of execution of main  destroyed when main function returns control to OS  may be "shadowed" by local variables with same name, so the global can't be accessed

Scope continued Why are global variables BAD?  cause "side effects" - allow a function to do something "behind your back"  what a function can affect / change should always be documented in its header  make it harder to reuse code - can't just pick up the code and copy it to another program  make it harder for people to work in teams

"Everything global" Do NOT be tempted to "make everything global" - it is a sure way to introduce bugs!!!! If a function header were "void PrintLine (int datavalue)" you would NOT expect it to change a variable called "totaldata", would you? with a global variable it can!

A Parameter or a Local Variable? How to decide  ask yourself "does this information need to COME FROM some other function?" = parameter  "does this information need to GO TO some other function?" = parameter or return value  "does ONLY this function need to know about this data?" = local

Questions Why is a function used for a task? To cut down on the amount of detail in your main program (encapsulation) Can one function call another function? Yes Can a function even call itself? Yes, that is called recursion; it is very useful and requires special care in writing

More Questions Does it make any difference what names you use for parameters? No; just use them in function body Do parameter names and argument names have to be the same? No

Documentation of Functions Short comment at prototype Header comment longer  purpose of function, using the names of all parameters and the return value if any  comment code in body as usual  pre and post conditions Sometimes put comment at closing brace that just has function name in it, makes it easier to match braces for the body