Functions Functions
prototypes prototypes
arguments arguments
overloading overloading
return values return values
part part II
Functions Functions
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.
Functions Functions
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
Function - an example Function - an example
{
int var1=1, var2=2, var3=3, var4=4;
function1(“ASU”, var1);
some statements;
function2(var4, var3);
function3(var2);
}
Function - an example Function - an example
void function1(char name, int place)
{ cout << name << “ is #” << place << endl;
}
void function2(int al, int mel)
{ cout <<“var3 x var4 = “ << mel / al<<endl;
}
void function3(int casey)
{ cout << casey << “ is the value in var2\n”;
}
Function properties Function properties
may be called
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
Functions Functions
1. #include <iostream.h>
2. void demofunction(void);
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. }
Function Function
Output
5. In main
6. (calls function - 11.) In Demo Function - 12.) Still in function.
7. Back in main
Line # Line #
* * * *
Function declaration Function declaration
double Pythagorus( double, double );
double Pythagorus( double, double );
data types only data types only
Function Syntax Function Syntax
Syntax
function header line function header
{{
statements
statements function bodyfunction body
}}
*
Function Header Syntax Function Header Syntax
Syntax
type function_name(parameters)type
no
;
Example Example
double
double Pythagorus(double a, double b)
Example Example
double Pythagorus(double a, double b)
Function Definition Function Definition
* * no
;
{
type var
{ double c;
c = sqrt(a*a + b*b);
return return c;
}
Function Call Function Call
void main(void) {
cout << “The hypotenuse is “
<< Pythagorus(12, 5);
}
OUTPUT
The hypotenuse is 13
Program Structure Program Structure
#include <iostream.h>
function prototypes;
void main(void) {
variable declarations;
statements
[including function calls]
}
function definition(s)
Function Prototypes Function Prototypes
Syntax
return type function_name(type);
Example Example
double
double PythagorusPythagorus((doubledouble,, double double););
*
Function Prototypes Function Prototypes
Examples Examples
double
double PythagorusPythagorus((doubledouble,, double double););
voidvoid do_stuffdo_stuff((voidvoid););
double
double times-emtimes-em((intint,, int int,, int int,, int int););
double
double myfuncmyfunc((doubledouble,, int int););
voidvoid print_emprint_em((charchar,, double double););
Function Calls Function Calls
Syntax Syntax
function_name(arguments);
Example Example
Pythagorus(3.0, 4.0);
* *
Function Calls Function Calls
find_max(firstnum, secnum);
get firstnum get firstnum
find_max( 865865
, ,
)get secnum get secnum
* * *
* * * 865865
firstnum firstnum
90909090 secnum secnum
memory memory
90909090
Function Calls Function Calls
answer = Pythagorus(3.0,4.0);
cout << “The hypotenuse = “ << answer << endl;
* cout << “The hypotenuse = “
<< Pythagorus(3.0,4.0)<<endl;
Function Calls Function 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 <<endl;* 100
Program Structure Program Structure
#include <iostream.h>
function prototypes;
void main(void) {
variable declarations;
statements
[including function calls]
}
function definition(s)
Program Structure Program Structure
main function square call cube call
square function cube function
#include <iostream.h>
square prototype square prototype
cube prototype cube prototype
Program Structure Program Structure
int square(int); // function prototype
int cube(int); // or function declaration void main(void)
{ int x = 8;
cout <<“The square is “<< square(x) <<‘\n’;square(x) cout <<“The cube is “ << cube(x) <<endl;cube(x)
. . .
}
int square(int n) // function definition { continued on next slide
Program Structure Program Structure
int 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 returnn*n*n;
n*n*n; *
Function Summary Function Summary
Prototype
typetype function_namefunction_name((parameter parameter typestypes))
; ;
Call
function_name
function_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)
* *
* * *
Function Overloading Function 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 Overloading Function Overloading
The functions must differ in their parameter lists. The type and/or number of parameters must be different.
Examples
double myFunction(int, int, int);
int myFunction(double, int, int);
int myFunction (double, double);
void myFunction(double);
*
Function Overloading Function 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);
{
c a l l
a double myFunction(int, int, int)
b int myFunction(double, int, int)
c int myFunction (double, double)
d void myFunction(double)
}
HeaderReturning Values Returning Values
A function can receive many values A function can receive many values
Only one value can be
Only one value can be directlydirectly returned returned
Returning Values Returning Values
The return statement:return
tells the function which value to send back to the calling program
terminates the function call and returns immediately to the calling program
Return Statement Return Statement
Syntax
return expression;
Examples
return c;
return hypotenuse;
Return Statement Return Statement
int find_max(int x, int y) { int maximum;
if (x >= y)
maximum = x;
elsemaximum = y;
return maximum;
}
same data type
*
Passing Data Passing Data
passing by value
gives a single value
passing by reference
may give back several values accomplished by
using references (this topic) using pointers
*
double Pythagorus(double a, double b) { double c;
c = sqrt(a*a + b*b);
return c;
}
Passing Data - by Value Passing Data - by Value
passing by value:
A copy of a value is passed from the calling copy 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_max call to find_max
value in first_num is passed
865
value in sec_num is passed
9090
Storing Values into Parameters
Storing 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, base(height, 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 Value Passing 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 Value Passing Data - by Value
*
back in main: cout << height;
cout << base:
4.0 3.0
Passing Data - by Value Passing Data - by Value
void 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 value
cout<<"Value at the end of the function is "<< q <<endl;
}
Passing Data - by Value Passing 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
Passing Data - by Reference Passing Data - by Reference
Syntax
double Pythagorus(double &, double & &); &
Pythagorus(height, base);
double Pythagorus(double& a, double& & b)&
function prototype
function call
function definition
void main(void)
{ double height = 4.0, base = 3.0;
double Pythagorus(double &, double & &);&
cout << “Hypotenuse = “
<< Pythagorus(height, base) << endl;
. . . }
double Pythagorus(double& a, double& & b)&
{ double c;
c = sqrt(a*a + b*b);
return c;
}
Passing Data - by Reference Passing Data - by Reference
* *
address address
of height of height
address address of base of base
double Pythagorus(double& a, double& & b)&
{ double c;
a++;b++;
c = sqrt(a*a + b*b);
return c;
}
Passing Data - by Reference Passing Data - by Reference
*
address address
of height of height
address address of base of base
back in main: cout << height;
cout << base:
Passing Data - by Reference Passing Data - by Reference
In main() values referenced as
1 value stored 1 value stored
a
height
1 value stored 1 value stored
b
base
In Pythagorus() values referenced as
*
Passing Data - by Reference Passing Data - by Reference
{ float a, b, c, sum, product;
void calc(float, float, float, float &, float &); // prototype
cout << "Enter three numbers: ";
cin >> a >> b >> c;
calc(a, b, c, sum, product); // call cout << a<<“ + “<<b<<“ + “c<<“ = " << sum;
cout << ‘\n’<<a<<“ * “<<b<<“ * “c<<“ = " << product;
}
void calc(float x, float y, float z, float &tot, float& multiply) { tot = x + y + z; // definition
multiply = x * y * z;
x++; y++; z--;// for demo purposes }
Passing Data - by Reference Passing Data - by Reference
Output
Enter three numbers: 5 7 9 5 + 7 + 9 = 21
5 * 7 * 9 = 315
* x is 6, y is 8, z is 8
tot and sum refer to the same address
product and multiply refer to the same address
Passing Data - by Reference Passing Data - by Reference
void main(void) { int w = 3;
void print_val(int &); // function prototype
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 value
cout<<"Value at the end of the function is "<< q <<endl;
}
Passing Data - by Reference Passing Data - by Reference
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 6
Swap Routine Swap Routine
void swap(float& num1, float& num2) {
float temp;
temp = num1;
num1 = num2;
num2 = temp;
}
Data Type Mismatch Data Type Mismatch
value parameters
implicit type conversion - value of the
actual parameter is coerced to the data type of the formal parameter
reference parameters
no coercion because an address is passed, not a value
* *
A Comparison A Comparison
formal actual
parameter is parameter may be
value variable, constant, or expression
type coercion may take place reference variable only
of exact same type as formal
What’s Happening????
What’s Happening????
call sequence
1. memory is allocated 2. parameters are passed 3. transfer of control
return sequence
1. value of the return is stored 2. memory is deallocated
3. transfer of control
* *
“ “ Louis Pasteur’s theory of Louis Pasteur’s theory of
germs is ridiculous fiction.”
germs is ridiculous fiction.”
Pierre Pachet Pierre Pachet
Professor of Physiology Professor of Physiology
Toulouse, 1872 Toulouse, 1872
End Note End Note
Copyright © 1997 by Freedom TLC, Inc.
Function Practice - I:
Function Practice - I: wholepart( ) wholepart( )
accepts a double
returns the integer part of any fraction Hint: Assign the passed argument to an integer variable.
Ex. 123.4567 returns 123
the calling function displays the result
Function Practice - I:
Function Practice - I: fracpart( ) fracpart( )
accepts a double
returns the fractional part of any number passed to it.
Ex. 123.4567 returns .4567
the calling function displays the result
Function Practice - I:
Function Practice - I: find_abs( ) find_abs( )
accepts a double
computes its absolute value
returns the value
calling function displays the result
Function Practice - I:
Function Practice - I: mult( ) mult( )
accepts two doubles
multiplies them
returns the result
calling function displays the result
Function Practice - I:
Function Practice - I: powfun( ) powfun( )
accepts two integers
raises the first to the power of the second
the returned value is a long integer
the calling function displays the result
Function Practice - I:
Function Practice - I: tempvert( ) tempvert( )
accepts a double
converts C to F or F to C
returns the converted temperature
the calling function asks
the direction of conversion the temperature to convert displays the result