Download Understanding Functions in C++: Headings, Prototypes, Calls, and Parameters and more Slides Advanced Computer Programming in PDF only on Docsity!
Chapter 7
Functions
Chapter 7 Topics
- Writing a Program Using Functional
Decomposition
- Writing a Void Function for a Task
- Using Function Arguments and Parameters
- Differences between Value Parameters and
Reference Parameters
- Using Local Variables in a Function
- Function Preconditions and Postconditions
Function Calls
One function calls another by using the name
of the called function followed by()s that
enclose an argument list, which may be
empty
A function call temporarily transfers control
from the calling function to the called
function
Function Call Syntax
FunctionName( Argument List )
The argument list is a way for functions to communicate
with each other by passing information
The argument list can contain 0, 1, or more arguments,
separated by commas, depending on the function
What is in a heading?
int Cube (int n)
type of value returned
name of function
parameter list
Prototypes
A prototype looks like a heading but must
end with a semicolon, and its parameter
list needs only to contain the type of each
parameter
int Cube(int ); // Prototype
#include int Cube(int); // prototype using namespace std; void main() { int yourNumber; int myNumber; yourNumber = 14; myNumber = 9; cout << “My Number = “ << myNumber; cout << “its cube is “ << Cube( myNumber) << endl; cout << “Your Number = “ << yourNumber; cout << “its cube is “ << Cube( yourNumber) << endl; } arguments
Successful Function Compilation
Before a function is called in your program,
the compiler must have previously
processed either the function’s prototype
or the function’s definition (heading and
body)
Example
Write a void function called DisplayMessage(),
which you can call from main(), to describe the
pollution index value it receives as a parameter
Your city describes a pollution index
less than 35 as “Pleasant”,
35 through 60 as “Unpleasant”,
and above 60 as “Health Hazard”
parameter
void DisplayMessage(int index) { if(index < 35) cout << “Pleasant”; else if(index <= 60) cout << “Unpleasant”; else cout << “Health Hazard”; }
Return Statement
return; // No value to return
• Is valid only in the body block of a void function
• Causes control to leave the function and
immediately return to the calling block, leaving any
subsequent statements in the function body
unexecuted
Header Files
Header Files contain
const int INT_MAX = 32767;
float sqrt(float);
string, ostream, istream
cin, cout
Value-Returning Functions #include int Square(int); // Prototypes int Cube(int); 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 calls 19
Rest of Program int Square(int n) // Header and body { return n * n; } int Cube(int n) // Header and body { return n * n * n; }