Escolar Documentos
Profissional Documentos
Cultura Documentos
2nd Edition
By Barbara Johnston
Chapter 4
Instructor: <Instructor Name>
Lecture Slides by Kelly Montoya and Rob Garner
Overview
Basic Function Characteristics
Types of functions
Calling and Called Functions
How to write functions
Return Statement
Function Calls
Function variables
Troubleshooting Functions
Overloaded Functions
Default Parameter Lists
Variable Scope
String Stream Class
Common Errors With Functions
Basic Function
Characteristics
Functions in C++
A function is a complete section (block)
of C++ code with a definite start point
and an end point between curly braces
and its own set of variables.
Functions can be passed data values
and they can return data.
Functions should be designed so that
they have one primary task to
accomplish.
Types of functions
Void Parameterless
Function
The following function, named
WriteHello() is passed nothing and
returns
Nothing
returned. nothing.No parameters.
void WriteHello()
{
cout << "\n Hello from a
function!";
}
Parameterless Function
that returns a value
int AskForAge()
cin statement
No parameters.
{
leaves the Enter
int age;
key in the input
queue.
cout << "\n How old are you? ";
cin.ignore()
cin >> age;
function
cin.ignore();
//remove enter keyremoved that
Enter key.
return age;
}
Return key word will return value in age.
Parameterless function
that returns a value
Zero parameters.
Data is read
into a string
object using
getline()
and age
Void so no
assignment
operator.
Concentrate on the
Function First
Concentrate on one function at a time.
Work as if you cant see other parts of
the program.
Each function is its own block of code,
with its own variables and control
statements.
Write the prototype, see if it can be
called, then write the function.
See how functions must be laid out in the source code file.
Function Declaration or
Prototype
Before a function can be called, the
calling function must know about the
called function.
The prototype may be declared in the
calling function before the call, it can
appear above the calling function or it
can appear in an include file.
The important point is that the compiler
must have seen the function prototype
before the function is called.
Function Declaration or
Prototype
The form of the function prototype is:
Return_type function_name(type param, );
RETURN STATEMENT
Return Statement
The return statement serves three
purposes in a C++ function.
It is required when the function is returning a
value to the calling function.
The return statement causes the program
control to exit the function and to return to
the calling function.
An expression may be evaluated within the
parentheses format of the return statement.
Return Statement
The return statement is way to terminate the
function and return to the calling function at
any point in the function body.
The return statement can be used to return a
value or to exit the function if nothing is
returned.
The return statement in CalcCost() is:
return totalCost;
Return Statement
The function WriteGreeting() does not
return a value to the calling function, so
no return statement is required:
void WriteGreeting()
{
cout << "\n Welcome to the C++"
<< " Hotel Rate Program"
<< "\n we offer a fine hotel on the beach.
\n";
}
Function Calls
Function Calls
The call statement is the C++ statement
where the called function is accessed.
When a function is called, control is
passed to the called function, and the
statements inside that function are
performed.
Control is returned to the calling
function when the function tasks are
completed.
The call statement requires that just the
variable names be used.
Function Calls
The function calls in the C++ Hotel
program are:
numPeople = HowManyPeople();
numNights = HowManyNights();
roomType = WhatTypeRoom();
totalCost = CalcCost(numPeople, numNights, roomType);
WriteCostSummary(numPeople, numNights, roomType,
totalCost);
Call by Value
A call by value copies the value of the
variable into the input parameter
variables of the called function when the
data is passed to the function.
In the C++ Hotel program, each function
has its own copy of the variables that it
needs.
Call by Value
Each function has its own copy of its variables. In the C++ Hotel program,
the number of people and cost are illustrated here.
numPeople
numNights
totalCost
roomType
num
le!
ariab
v
e
am
he s
Not t
num
Function variables
Function Variable
ownership
Variable names do not have to be the
same from function to function. The Sum
1 to N program shows this.
The main() function has the variables
x and sum.
In the Get_Number() function, the
variable holding the users number is
number
In the Add_1_to_N(), the number is just
n.
Function Variable
ownership
int Get_Number() //Function header line
{
// returns number
int number;
cout <<"\n Enter a number ";
cin >> number;
return number;
}
Function Variable
ownership
int Add_1_to_N(int n) //Function header line
{
// input is n
int total = 0,i;
for(i = 1; i <= n; ++i)
{
total = total + i;
}
return total;
}
Function Variable
ownership
Parameter in
function definition is
called n here it is
passed in as an
int main()
argument called x.
{
int x,sum;// using names x and sum
x = Get_Number();//call to function to get the user's
number
sum = Add_1_to_N(x);
//pass x, adder returns the sum
cout << "\n The result from adding 1 + 2 + ... + "
<< x << " is " << sum << endl;
return 0;
}
Function Variable
ownership
The sum value in main is represented as
the total value in the Add_1_to_N()
function.
When variables are declared in a
function header line or within the
function itself, the variables are local to
(are owned by) that function.
They are not seen by any other function.
Function Variable
ownership
sum
number
total
36
28
21
15
10
6
3
1
8
7
6
5
4
3
2
1
Troubleshooting
Functions
Troubleshooting:
Undeclared identifier
A data variable declared inside main()
cant be seen by all other functions.
Remember, that each standalone
function must have its own data
variables.
Compiler errors:
asknameagefunc.cpp(47) : error C2065: 'age' :
undeclared identifier
asknameagefunc.cpp(56) : error C2065:
'name' : undeclared identifier
int main()
{
int age;//this is mains age, name
string name;
age = AskForAge();
name = AskForName():
//rest of main
}
int AskForAge()//variable for age not here
{
cout << "\n How old are you?";
cin >> age;//compiler error here!
return age;
}
string AskForName()
//variable for name not here
{
cout << "\n What is your name?";
getline(cin, name);//compiler error here!
return name;
}
Overloaded Functions
Overloaded Functions
Overloaded functions make it possible to
have two or more functions with the
same name but with different input
parameter lists.
Overloaded functions all have perform
essentially the same jobbut there are
different input possibilities.
Overloaded functions give us several
possible functions, and due to some
condition, we dont necessarily use all of
them.
DrawLines(@, 30);
line
DrawLines(#,15,3);
DrawLines(%,6);
//vary the second value,
//must have the first
Variable Scope
Local Variables
The variables declared within the
function and in the function header line
input list belong to that function.
No other function can see, access, or
change these variables.
These local variables come into
existence when the function begins
executing and are destroyed once
program control exits the function.
Also known as Automatic variables.
Block Scope
When you declare a variable inside a set
of braces { } that variable then exists
inside that block of code.
Once code execution moves beyond
those braces, the variable goes out of
scope.
It also shows the regions where the
variables are in scope.
name
Bob
count
count
1
2
3
4
0
5
Hi bob
Hi bob
Hi bob
Hi bob
Hi bob
Global Variables
A global variable is declared outside any
function and is visible to all functions in
that program file.
All the functions can use and change a
global variable.
Global variables are declared above
main().
There is no need to pass them between
functions.
Global Variables
global variables
declared outside
functions
int age;
string name;
int main()
{
WriteHello(); //Write a greeting
AskForName();
Global Variables
Functions do not pass or return
anything
since they are working with global
variables.
//Function Prototypes
void
void
void
void
WriteHello();
AskForName();
AskForAge();
Write();
Function definitions
//AskForAge asks the user for age, returns
age.
void AskForAge()
{
cout << "\n How old are you? ";
cin >> age;
cin.ignore();
//remove enter key
}
//AskForName asks the user's name
void AskForName()
{
cout << "\n What is your name? ";
getline(cin,name);
}
Static Variables
Once a variable is declared a static
variable, the variable contents are
retained until the program is terminated.
The variable is still visible only to the
function and it is not seen by any other
parts of the program.
The first time the function is entered,
the static variable initialization occurs.
Static Variables
If there is no initial value assigned in the code,
C++ initializes the static variable to zero.
The static variable initialization statement is
performed only once while the program is
running.
If a function must remember a value, even
after the program control has left that
function, a static variable will keep its value
until the program ceases to run.
The format is:
static float total =
static_cast<float>;
Static Variables
float HowMuchHaveYouSpent()
{
//total is set to zero 1st time in here
static float total = static_cast<float>(0.0);
float amount;
cout << "\n How much was this recent purchase?
";
cin >> amount;
cin.ignore();
In this example, only this function sees total. Every time it is called,
it remembers the value and keeps adding it to the previous total.
places is ";
Output
Welcome to the StringStream Demo program.
Here is our formatted text string:
A dozen is 12, a dollar is $1.00 and
the value of pi to 10 places is 3.1415926536.
Here is the final string:
A dozen is 12, a dollar is $1.00 and
the value of pi to 10 places is 3.1415926536.
There are 2 "+"s in C++.
The function prototype and call statements do not match in the input lists.
The prototype, call statement and function header lines have to match.
Leaving the semi-colon on the function header line generates this error.
Review
Functions require two sets of statements: a
prototype or declaration, and a function
definitionwhich is the actual function code.
The first line of the function is named the
function header line.
The function prototype, or declaration, and
function header line are almost identical.
They contain the return data type and input
data type variable, list parameters.
The call statement is the location where the
function is actually called.
Review
The call requires only variable names.
If a value is returned, it should be assigned into
a variable.
Functions can be overloaded, meaning that two
or more functions can have the same name but
they must have different input parameter lists.
The function prototype can have default values
assigned to the input variables. When you have
default values you do not need to have values
or variables in the call statements.
Review
Global variables are declared outside any
function and are seen by all functions in
the file.
Local variables are declared inside the
function or in the function header line
and are only accessible within the
function.
Static variables are local variables that
retain their value after the function is
exited.
Summary
Basic Function Characteristics
Types of functions
Calling and Called Functions
How to write functions
Return Statement
Function Calls
Function variables
Troubleshooting Functions
Overloaded Functions
Default Parameter Lists
Variable Scope
String Stream Class
Common Errors With Functions