1.26k likes | 2.93k Views
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);
E N D
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 Arguments Parameters Always appear in a function call within the calling block Always appear in the function heading, or function prototype
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 <iostream> 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