Chapter 6 Functions

advertisement
Chapter 6:
Functions
Outline
•
•
•
•
What is “Function”
Sending data into function
The return statement
Local and Global variables
Modular Programming
• Modular programming: breaking a program up into
smaller, manageable functions or modules
• Function: a collection of statements to perform a task
• Motivation for modular programming:
– Improves maintainability of programs
– Simplifies the process of writing programs
– In summary: Modular programs are easier to develop,
modify and maintain than programs constructed otherwise
Slide 6- 3
Slide 6- 4
main() – driver function
• To provide for the orderly
placement and execution of
functions,
each
C++
program must have one and
only one function named
main().
The main()
function is referred to as a
driver function because it
directs or "drives" the other
modules or functions in the
order in which they are to
be executed
Function Definition
Slide 6- 8
Function Return Type
• If a function returns a value, the type of the
value must be indicated:
int main()
• If a function does not return a value, its
return type is void:
void printHeading()
{
cout << "Monthly Sales\n";
}
Slide 6- 9
Function Return Type
• The return statement can then be eliminated from
the main ( ) function. The structure of main( ) can be
as follows:
void main( )
{
//program statements go here;
}
Function example
#include<iostream>
using namespace std;
/*********************
//define a function *
*********************/
void display_message()
{
cout<< "Hello from the function displaymessage.\n";
}
/*********************
//main function *
*********************/
void main()
{
cout<<"hello world!! from main function.\n";
display_message();
}
Calling a Function
void printHeading()
{
cout << "Monthly Sales\n";
}
• To call a function, use the function name followed by ()and ;
printHeading();
• When called, program executes the body of the called
function
• After the function terminates, execution resumes in the
calling function at point of call.
Slide 6- 15
Function Prototypes
• Ways to notify the compiler about a function
before a call to the function:
1. Place function definition before calling function’s
definition
or
2. Use a function prototype (function declaration) – like
the function definition without the body
• Header: void printHeading()
• Prototype: void printHeading();
Slide 6- 17
(Program Continues)
Slide 6- 18
Slide 6- 19
Outline
•
•
•
•
What is “Function”
Sending data into function
The return statement
Local and Global variables
Sending Data into a Function
• Can pass values into a function at time of call:
displayValue(5);
// function call
• Values (data) passed to function are arguments
• Variables in a function that hold the values passed as
arguments are parameters
void displayValue(int num)
{
cout << "The value is " << num << endl;
}
The integer variable num is a parameter. It accepts any integer
value passed to the function.
Slide 6- 22
What is the output?
Slide 6- 23
The function call in line 11 passes the value 5
as an argument to the function.
Slide 6- 24
Parameters, Prototypes, and Function
Headers
• For each function argument,
– the prototype must include the data type of each
parameter inside its parentheses
– the header must include a declaration for each
parameter in its ()
void evenOrOdd(int);
//prototype
void evenOrOdd(int num) //header
evenOrOdd(val);
//call
Slide 6- 25
Passing Multiple Arguments
When calling a function and passing multiple
arguments:
– the number of arguments in the call must match
the prototype and definition
– the first argument will be used to initialize the first
parameter, the second argument to initialize the
second parameter, etc.
Slide 6- 26
Slide 6- 27
The function call in line 18 passes value1, value2, and
value3 as arguments to the function.
Slide 6- 28
Passing Data by Value
• Example:
int val=5;
evenOrOdd(val);
val
5
argument in
calling function
num
5
parameter in
evenOrOdd function
int evenOrOdd (int num)
{…
num = num+10; …}
• evenOrOdd can change variable num, but it will have no
effect on variable val
Slide 6- 30
Outline
•
•
•
•
What is “Function”
Sending data into function
The return statement
Local and Global variables
The return Statement
The RETURN statement has two purposes:
• The return statement causes a function to
END immediately
• A function may send ONE value back to the
part of the program that called the function
Slide 6- 32
The return Statement
• Used to end execution of a function
• Can be placed anywhere in a function
– Statements that follow the return statement
will not be executed
• Can be used to prevent abnormal termination
of program
• In a void function without a return
statement, the function ends at its last }
Slide 6- 33
(Program Continues)
Slide 6- 34
Program 6-11(Continued)
Slide 6- 35
Returning a Value From a Function
• A function can return a value back to the statement that
called the function.
• A function returning a value must specify, in its header
line, the data type of the value that will be returned.
• In a value-returning function, the return statement can
be used to return a value from function to the point of call.
Example:
int sum(int num1, int num2)
{
int result;
result = num1 + num2;
return result;
}
Slide 6- 36
A Value-Returning Function
Return Type – Incorrect
int sum(int num1, int num2)
{
double result;
result = num1 + num2;
return result;
}
Value Being Returned
Slide 6- 37
A Value-Returning Function
Return Type – Correction – Depending on
design of code
double sum(int num1, int num2)
{
double result;
result = num1 + num2;
return result;
}
Value Being Returned
Slide 6- 38
A Value-Returning Function
Return Type – Correction – Depending on
design of code
int sum(int num1, int num2)
{
int result;
result = num1 + num2;
return result;
}
Value Being Returned
Failure to match the return value exactly with the function's declared data
type may not result in an error when the program is compiled, but it may
lead to undesired results because the return value is always converted to the
data type declared in the function declaration
Slide 6- 39
Calling function to receive the value
• On the receiving side, the called function must:
– be alerted to the type of value to expect
– properly use the returned value
• provide a variable to store the value
– accomplished by using a standard assignment statement, e.g.:
total = sum (firstnum, secondnum);
• use the value directly in an expression, e.g.:
cout << sum(firstnum, secondnum);
The next program illustrates the inclusion of both the prototype and
assignment statements for main( ) to correctly call and store a
returned value from sum( ).
int findSum(int, int);
int main ( void )
{
int firstnum, secondnum, total;
//the function prototype
cout << "Please enter your first number to be added: ";
cin >> firstnum;
cout << "Good Job!! Please enter your second number to be added: ";
cin >> secondnum;
total = findSum(firstnum, secondnum);
//the function is called here
cout << "The sum of the two numbers you have entered is " << total;
return 0;
}
int findSum(int number1, int number2)
{
int sum;
sum = number1 + number2;
return sum;
}
//function header line
//start of function body
//variable declaration
//calculates the sum
//return statement
//function prototypes
double inputFahrenheit( );
//reads fahrenheit temp from user
double convertFahenheitToCelsius(double); //converts fahren temp to celsius
void displayConvertedDegree (double, double); //displays converted temperature
int main ( void )
{
//Declaration statements
double fahrenheit = 0.0; //stores the temp in fahren entered by user
double celsius = 0.0;
//stores the calculated converted temp in celsius
fahrenheit = inputFahrenheit( ); //function call to get data from user
celsius = convertFahenheitToCelsius(fahrenheit);//function call-convert F˚ to celsius
displayConvertedDegree(celsius, fahrenheit); //function call -display converted temp
return 0;
}
/* This function allows the user to input the temperature in Fahrenheit that is to be converted to Celsius */
double inputFahrenheit( )
{
double f;
cout << "Please enter the temperature recorded in Fahreheit " << endl << "that you wish to be converted to
Celsius: ";
cin >> f;
return f;
}
/* This function converts Fahrenheit to Celsius */
double convertFahenheitToCelsius(double f_degrees)
{ return (5.0 / 9.0 ) * ( f_degrees - 32.0 ); }
/*This function displays Celsius equivalent of the temperture that was entered in Fahrenheit */
void displayConvertedDegree(double cel, double fahren)
{ cout << fahren << " Fahrenheit is " << cel << " Celsius. " << endl;}
• Output:
Please enter the temperature recorded in Fahreheit
that you wish to be converted to Celsius: 32
32 Fahrenheit is 0 Celsius.
• This program consists of 4 functions
main( )
inputFahrenheitToCelsius( )
convertFahrenheitToCelsius( )
displayConvertedDegree( )
Outline
•
•
•
•
What is “Function”
Sending data into function
The return statement
Local and Global variables
Local Variables
Slide 6- 52
When the program is executing in main, the num variable defined in main is
visible. When anotherFunction is called, however, only variables defined inside it are
visible, so the num variable in main is hidden.
Slide 6- 53
Global Variables
• A global variable is any variable defined
outside all the functions in a program.
• The scope of a global variable is the portion of
the program from the variable definition to
the end.
• This means that a global variable can be
accessed by all functions that are defined
after the global variable is defined.
• Constant variable is a good example for global
variable
Slide 6- 55
Global Variables
• You should avoid using global variables because they make
programs difficult to debug.
– Global variables allow the programmer to "jump around" the normal
safeguards provided by functions. Rather than passing variables to a
function, it is possible to make all variables global ones. DO NOT DO
THIS. By making all variables global, you instantly destroy the
safeguards that C++ provides to make functions independent and
insulated from each other, including the necessity of carefully
designating the type of parameters a function needs, the variables
used in the function, and the value returned. Using only global
variables can be especially disastrous in larger programs that have
many functions. A global variable can be accessed and changed by any
function following the global declaration which makes it timeconsuming and frustrating to locate the origin of an erroneous value in
a large program
Slide 6- 56
Download