Top Banner
Functions in C+ + Top Down Design with Functions
34

Functions in C++

Jan 18, 2016

Download

Documents

Celina Nitu

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); - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Functions in C++

Functions in C++

Top Down Design with Functions

Page 2: Functions in C++

Top-down Design

Big picture first broken down into smaller pieces

Page 3: Functions in C++

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;

}

Page 4: Functions in C++

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

Page 5: Functions in C++

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?

Page 6: Functions in C++

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?

Page 7: Functions in C++

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?

Page 8: Functions in C++

Function prototype example:

float myfun (float one, float two);

// assumes cmath has been included

Page 9: Functions in C++

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!

Page 10: Functions in C++

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

Page 11: Functions in C++

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!

Page 12: Functions in C++

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

Page 13: Functions in C++

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

Page 14: Functions in C++

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

Page 15: Functions in C++

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

Page 16: Functions in C++

Some important points about function call semanticsArguments 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

Page 17: Functions in C++

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

Page 18: Functions in C++

Classified by Location

Always appear in a function call within the calling block

Always appear in the function heading, or function prototype

Arguments Parameters

Page 19: Functions in C++

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!

Page 20: Functions in C++

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

Page 21: Functions in C++

Value-Returning Functions#include <iostream>int Square(int n); // Prototypesint 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 calls21

Page 22: Functions in C++

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

int Cube(int n) // Header and body{ return n * n * n;}

Page 23: Functions in C++

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

Page 24: Functions in C++

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 returnDestroy locals and copies of arguments

9. Return control to statement AFTER call

Page 25: Functions in C++

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

Page 26: Functions in C++

Scope continued

Local variablescreated every time the function runs initializations done every time they are

createddestroyed when the function returns control

Page 27: Functions in C++

Scope continued

Parametersname is known from header line until end of

function bodyNAME 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

Page 28: Functions in C++

Scope continued

Global variablesdeclared outside of any function at allknown from point of declaration in file to end

of FILEallocated space at start of execution of maindestroyed when main function returns control

to OSmay be "shadowed" by local variables with

same name, so the global can't be accessed

Page 29: Functions in C++

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

Page 30: Functions in C++

"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!

Page 31: Functions in C++

A Parameter or a Local Variable?

How to decideask 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

Page 32: Functions in C++

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

Page 33: Functions in C++

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

Page 34: Functions in C++

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 usualpre 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