Lecture 56
Lecture 56
Programs written by
combining new functions with “prepackaged” functions in
the C++ standard library.
new classes with “prepackaged” classes.
The standard library provides a rich collection of
functions.
Functions are invoked by a function call
A function call specifies the function name and provides
information (as arguments) that the called function needs
Boss to worker analogy:
A boss (the calling function or caller) asks a worker (the
called function) to perform a task and return (i.e., report
back) the results when the task is done.
Program Components in C++
Function definitions
Only written once
These statements are hidden from other
functions.
Boss to worker analogy:
The boss does not know how the worker
gets the job done; he just wants it done
Functions
Functions
Allow the programmer to modularize a
program
Local variables
Known only in the function in which they are
defined
All variables declared in function definitions
are local variables
Parameters
Local variables passed when the function is
called that provide the function with outside
information
Functions
1 4 9 16 25 36 49 64 81 100
1 // Fig. 3.4: fig03_04.cpp
2 // Finding the maximum of three integers
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 int maximum( int, int, int ); // function prototype
10
11 int main()
12 {
13 int a, b, c;
14
15 cout << "Enter three integers: ";
16 cin >> a >> b >> c;
17
18 // a, b and c below are arguments to
19 // the maximum function call
20 cout << "Maximum is: " << maximum( a, b, c ) << endl;
21
22 return 0;
23 }
24
25 // Function maximum definition
26 // x, y and z below are parameters to
27 // the maximum function definition
28 int maximum( int x, int y, int z )
29 {
30 int max = x;
31
32 if ( y > max )
33 max = y;
34
35 if ( z > max )
36 max = z;
37
38 return max;
39 }
or
Function overloading
Having functions with same name and different
parameters
Should perform similar tasks ( i.e., a function to
square ints, and function to square floats).
int square( int x) {return x * x;}
float square(float x) { return x *
x; }
Program chooses function by signature
signature determined by function name and
parameter types
Can have the same return types