Functions in C Top Down Design with Functions

  • Slides: 34
Download presentation
Functions in C++ Top Down Design with Functions

Functions in C++ Top Down Design with Functions

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

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

Can you tell what this is doing? int main () { rad = get_a_number();

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 n put details off while

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

Suppose you had some code that looked like this: side 2 = pow(a, 2)

Suppose you had some code that looked like this: side 2 = pow(a, 2) + pow (b, 2); side 4 = pow(c, 2) + pow (side 2, 2); side 7 = pow(b, 2) + pow (side 4, 2); side 3 = pow(5. 3, 2) + pow (side 2, 2); cout << pow (19. 2, 2) + pow(angle 3, 2) + angle 9; n 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

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 side 2 = myfun (a, b);

Function call examples: // the code before becomes side 2 = myfun (a, b); side 4 = myfun (c, side 2); side 7 = myfun (b, side 4); side 3 = myfun (5. 3, side 2); cout << myfun (19. 2, angle 3) + angle 9; n could you name the arguments?

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

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

Value-returning Function Syntax The Definition n has header "return type" "name" ( parameter list

Value-returning Function Syntax The Definition n has header "return type" "name" ( parameter list ) n has body - must be between braces n body must have return x; where x is a constant or variable or expression n 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)"

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 n just like header except ends with semicolon "float

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

Value-returning Function Semantics A function is a control structure so how does it change

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

Value-returning Function Semantics x = myfun (5. 0, angle 3) * 17. 2; 1.

Value-returning Function Semantics x = myfun (5. 0, angle 3) * 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, angle 3 to two 5. Any local variables declared are given space

Value-returning Function Semantics x = myfun (5. 0, angle 3) * 17. 2; 6.

Value-returning Function Semantics x = myfun (5. 0, angle 3) * 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, angle 3) * 17. 2; 9.

Value-returning Function Semantics x = myfun (5. 0, angle 3) * 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

Some important points about function call semantics Arguments and parameters are matched up by the compiler: n as to type - corresponding args and parms must match or be able to be converted n as to quantity - must have same number of args and parms n 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

Some important points about function call semantics Note that NAMES of arguments and parameters do NOT have to match! n 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 n Arguments are in function calls, Parameters are in function definitions or prototypes n

Classified by Location Arguments Always appear in a function call within the calling block

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

Arguments / Parameters They are the interface between the function and the "outside world"

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

What is "an overloaded function"? You can have more than one function with the

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 n The compiler figures out which one you mean by the arguments you send n If it can't distinguish which one you mean, then you get an error n 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 n

Value-Returning Functions #include <iostream> int Square(int n); int Cube(int n); using namespace std; //

Value-Returning Functions #include <iostream> int Square(int n); int Cube(int n); using namespace std; // Prototypes 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) { return n * n; } // Header

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

Void function semantics Simpler than value-returning but similar 1. call is from a stand-alone

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.

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? " n Parameters n ¨ from header line

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

Scope continued n Local variables ¨ created every time the function runs ¨ initializations

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

Scope continued n Parameters ¨ name is known from header line until end of

Scope continued n 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 n Global variables ¨ declared outside of any function at all ¨

Scope continued n 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 n Why are global variables BAD? ¨ cause "side effects" - allow

Scope continued n 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

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

A Parameter or a Local Variable? n How to decide ¨ ask yourself "does

A Parameter or a Local Variable? n 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

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

More Questions Does it make any difference what names you use for parameters? No;

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

Documentation of Functions Short comment at prototype n Header comment longer n ¨ purpose

Documentation of Functions Short comment at prototype n Header comment longer n ¨ 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 n Sometimes put comment at closing brace that just has function name in it, makes it easier to match braces for the body