functions g prototypes g arguments g overloading g return values part i re-read section 1.2

Post on 05-Jan-2016

218 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

FunctionsFunctions prototypesprototypes

argumentsarguments

overloadingoverloading

return valuesreturn values part part

IIRe-read Section 1.2

Functions, again!Functions, again!

are subprograms in C++ . perform a specific task. can act on data and return a value. Every C++ program has at least one

function: main().

* * * *

are self-contained blocks of code, the inner workings of which are invisible to the remainder of the program.

FunctionsFunctions

Why use functions? make programs easier to write, debug and

maintain - divide and conquer!

*

Two main types of functions: predefined -- found in the header files user-defined -- today’s topic

Functions – I REPEAT!Functions – I REPEAT!

are subprograms in C++ . perform a specific task. can act on data and return a value. Every C++ program has at least one

function: main().

* * * *

are self-contained blocks of code, the inner workings of which are invisible to the remainder of the program.

FunctionsFunctions

Why use functions? make programs easier to write, debug and

maintain - divide and conquer!

*

Two main types of functions: predefined (library functions) found in

the header files & the C++ library user-defined – make your own, include it

yourself

Functions - an exampleFunctions - an example

{int var1=1, var2=2, var3=3, var4=4;function1(‘A’, var1); (‘A’, var1); //Call the function//Call the functionsome statements;function2(var4, var3); (var4, var3); //Call //Call function3(var2); (var2); //Call //Call

}Arguments to the functions

Function - an exampleFunction - an example

void function1(char grade, int place){ cout << grade << “ is #” << place << endl;}

void function2(int ml, int m2){ cout <<“var3 x var4 = “ << m1 * m2<<endl;}

void function3(int Upick){ cout << Upick << “ is the value in var2\n”;}

Function propertiesFunction properties

may be called (multiple times) may be passed data called arguments may return a value to the calling

program will not change the data stored in a

received variable unless specifically instructed to do so

FunctionsFunctions 1. #include <iostream> using namespace std; 2. void demofunction(void); //prototype 3. void main(void) 4. { 5. cout << "In main\n"; 6. demofunction(); 7. cout << "Back in main\n"; 8. }

9. void demofunction(void) 10. { 11. cout << "In DemoFunction\n"; 12. cout << “Still in function.\n”; 13. }

FunctionFunction

Output

5. In main

6. (calls function - 11.) In Demo Function

- 12.) Still in function.

7. Back in main

Line #Line #

* * * *

Function declaration (prototype)Function declaration (prototype)

double Pythagorus( double, double );double Pythagorus( double, double );

data types onlydata types only

semicolon

Function identifier – its name

Function Definition SyntaxFunction Definition Syntax

Syntax

function header line function header

{{statementsstatements function bodyfunction body

}}

*

Function Header SyntaxFunction Header Syntax

Syntax

typetype function_name(parameters)

no ;ExampleExample

doubledouble Pythagorus(double a, double b)

ExampleExample

double Pythagorus(double a, double b)

Function DefinitionFunction Definition

* *

no ;{type var

{double c;

c = sqrt(a*a + b*b);returnreturn c;

}

Communication into function

Communication out of function

Function CallFunction Call

void main(void){

cout << “The hypotenuse is “<< Pythagorus(12, 5);

}

OUTPUTThe hypotenuse is 13

Program StructureProgram Structure

#include <iostream.h>function prototypes;

void main(void){

variable declarations;statements[including function calls]

}

function definition(s)

Function PrototypesFunction Prototypes

Syntaxreturn type function_name(type);

ExampleExampledoubledouble PythagorusPythagorus((doubledouble,, double double););

*

Need

Function PrototypesFunction Prototypes

ExamplesExamples

doubledouble PythagorusPythagorus((doubledouble,, double double););

voidvoid do_stuffdo_stuff((voidvoid););

doubledouble times-emtimes-em((intint,, int int,, int int,, int int););

doubledouble myfuncmyfunc((doubledouble,, int int););

voidvoid print_emprint_em((charchar,, double double););

Function CallsFunction CallsSyntaxSyntax

function_name(arguments);

ExampleExamplePrintPayCheck(employeeID,

Amount);

hyp = Pythagorus(3.0,4.0);

big = find_max(a,b);

* *

Return from function assigned to variables

Function CallsFunction Calls

find_max(firstnum, secnum);

get f

irstn

um

get f

irstn

um

find_max( ,, )865865

get s

ecnu

m

get s

ecnu

m

* * * * * *

865865firstnumfirstnum

90909090secnumsecnum

memorymemory

90909090

Function CallsFunction Calls

answer = Pythagorus(3.0,4.0);cout << “The hypotenuse = “

<< answer << endl;

*

cout << “The hypotenuse = “ << Pythagorus(3.0,4.0)<<endl;

Function CallsFunction Calls

answer = Pythagorus(3.0,4.0);answer answer = answer * 100; answer * 100;cout << “The hypotenuse = “

<< answer << endl;

*

cout << “Hypotenuse = “ << Pythagorus(3.0,4.0) * 100* 100 <<endl;

Program StructureProgram Structure

#include <iostream.h>function prototypes;

void main(void){

variable declarations;statements[including function calls]

}

function definition(s)

Program StructureProgram Structure

main functionsquare callcube call

square function

cube function

#include <iostream>

square prototypesquare prototypecube prototypecube prototype

Program StructureProgram Structureint square(int); // function prototypeint cube(int); // or function declaration

void main(void){

int x = 8;cout <<“The square is “<< square(x) square(x) <<‘\n’;cout <<“The cube is “ << cube(x) cube(x) <<endl;

. . .}

int square(int n) // function definition{ continued on next slide

Program StructureProgram Structureint square(int n) // function definition{

int answer;answer = n*n;return answer;

}

int cube(int n) // function definition{

int answer;answer = n*n*n;return answer;

}

{{OROR return n*n;return n*n;

{{OROR return n*n*n;return n*n*n;

*

Function SummaryFunction SummaryPrototype

typetype function_namefunction_name((parameter parameter typestypes));;

Callfunction_namefunction_name((actualactual parametersparameters));;

Definition formalformal typetype function_namefunction_name((parameter parameter types types & names)names){

}

double Pythagorus(double, double);

Pythagorus(height, base);

double Pythagorus(double a, double b) * * * * *

The challenge!The challenge!

Look at the Function Exercises following 6.1

Pages 238 and 239

Do any or all of Exercises 2, 4, or 6.

Run and test your programs

ONE of these will be part of your next programming assignment.

Function OverloadingFunction Overloading

Two or more distinct functions may have the same name.

The data types of the arguments in the function calls must match those in the prototypes and in the definitions.

The same function is given multiple definitions or implementations. The correct one is chosen by the compiler, not the programmer.

* * *

Function OverloadingFunction Overloading

The functions must differ in their parameter lists. The type and/or number of parameters must be different.

Examplesdouble myFunction(int, int, int);int myFunction(double, int, int);int myFunction (double, double);void myFunction(double);

*

Function OverloadingFunction Overloading

* * * *

.

// a is used// c is used// b is used// d is used

myFunction(3,4,5);myFunction(3.0, 4.0);myFunction(11.1, 9, 2);myFunction(23.56);{call

a double myFunction(int, int, int)b int myFunction(double, int, int)c int myFunction (double, double)d void myFunction(double)

}Header

Returning ValuesReturning Values

A function can receive many valuesA function can receive many values

Only one value can be Only one value can be directlydirectly returned returned

Returning ValuesReturning Values

The returnreturn statement: tells the function which value to send back

to the calling program terminates the function call and returns

immediately to the calling program

Return StatementReturn Statement

Syntaxreturn expression;

Examplesreturn c;

return hypotenuse;

Return StatementReturn Statement

int find_max(int x, int y){

int maximum;

if (x >= y)maximum = x;

elsemaximum = y;

return maximum;}

same data type

*

Passing DataPassing Data

passing by valuegives a single value

passing by referencemay give back several valuesaccomplished by

using references (this topic)using pointers

*

The The NOTNOT rule for functions rule for functions

The arguments in the function prototype, the function call, and the function header must

agree in number, order, and type

Remember this rule!

double Pythagorus(double a, double b){

double c;c = sqrt(a*a + b*b);return c;

}

Passing Data - by ValuePassing Data - by Value

passing by value:A copycopy of a value is passed from the calling function to the called function.

* *

double Pythagorus(double a, double b){

a = a * a;b = b * b;double c = sqrt(a*a + b*b);return c;

}

x

find_max(x, y)find_max(x, y)

arguments

y

* *

find_max(firstnum, secnum);find_max(firstnum, secnum);

call to find_maxcall to find_max

value in first_num is passed

865

value in sec_num is passed

9090

Storing Values into ParametersStoring Values into Parameters

void main(void)void main(void){{ double height = 4.0, base = 3.0;double height = 4.0, base = 3.0;

double Pythagorus(double, double);double Pythagorus(double, double);

cout << “Hypotenuse = “cout << “Hypotenuse = “<< << PythagorusPythagorus((height, baseheight, base)<<endl;)<<endl;. . .. . .

}}

double Pythagorus(double Pythagorus(double adouble a,, double b double b)){{ double c;double c;

c = sqrt(a*a + b*b);c = sqrt(a*a + b*b);return c;return c;

}}

Passing Data - by ValuePassing Data - by Value

* *

4.0 3.0

double Pythagorus(double a, double b){ double c;

a++;b++;

c = sqrt(a*a + b*b);return c;

}

Passing Data - by ValuePassing Data - by Value

*

back in main: cout << height;cout << base:

4.0 3.0

Passing Data - by ValuePassing Data - by Valuevoid print_val(int); // function prototype

void main(void){ int w = 3;

cout <<"w before the function call is "<<w<<‘\n’; print_val(w);

cout <<"w after the function call is "<<w<<‘\n’;}

void print_val(int q){ cout<<"Value passed to the function is "<<q<<endl;

q = q *2; // doubles the valuecout<<"Value at the end of the function is "<< q <<endl;

}

Passing Data - by ValuePassing Data - by Value

Output

w before the function call 3

Value passed to the function is 3

Value at the end of the function is 6

w after the function call is 3

““Louis Pasteur’s theory of Louis Pasteur’s theory of germs is ridiculous fiction.”germs is ridiculous fiction.”

Pierre PachetPierre PachetProfessor of PhysiologyProfessor of PhysiologyToulouse, 1872Toulouse, 1872

End NoteEnd Note

Copyright © 1997 by Freedom TLC, Inc.

top related