Você está na página 1de 88

C++ Programming Today

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

Describe the basic characteristics of


functions in C++

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.

Three Important Questions


What is the function supposed to do? (Whos job
is it? )
If a function is to read all data from a file, that function
should open the file, read the data, and close the file.

What input values does the function need to do


its job?
If your function is supposed to calculate the volume of
a pond, youd need to give it the pond dimensions.

What will my function return to me?


What will the function give you when it has finished its
task?

Functions: Basic Format


return_type function_name(input parameter
list)
{
// Body of function
}

The return_type is the data type of the value


returned from the function.
The function_name is the identifier (name)
of the function and is used to access the
function.
The input parameter list is the list of the
input variable data types and names that
the function receives.

Identify different types of functions

Types of functions

Three examples of simple


functions

All functions in C++ follow


this basic format.
The function name must follow standard C++
naming conventions.
There may be one return type.
If there is no return type, the void data type is
used.
The input argument list must have data type and
names (separated by commas)
You may pass in as many arguments as you like.
If your list is empty (no arguments are passed),
the parentheses will be empty () but still required

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()

Return key word will return value in name.

Functions with parameters


The input parameter list
that returns voidhas
two data items :name
It doesnt return
anything

and age

void Write(string name, int age)


{
cout << "\n Hi " << name << "! You
are "
<< age << " years old. \n";
}

The Write functions job is to


write the users name and age to
the screen

Explain the distinction between calling and called functions.

Calling and Called


Functions

Calling and Called


Functions
The terms calling function and called
function are often used when referring
to functions.
When one function (Function1) accesses
another function (Function2), it is said
that Function1 calls Function2.
That is, Function1 is the calling function
and Function2 is the called function.

Calling and Called


Functions
In order to invoke (make use of) the function,
youll need to have a statement that calls it.
The calling statement is the code located in
the program where the function is to be used
or accessed.
Depending on the requirements for the
function (input list) and return typeyour
function calls may vary in appearance.
In the example, main() calls all other
functions.

Calling and Called


Functions Calling function
is main.
Called function
is AskForName
String return
type so
assigned
into name.

Void so no
assignment
operator.

Explain how to write functions.

How to write functions

Every function must have:


Function prototype/declaration statement
which tells the compiler the function
name, and its return and input types.
Function definition/body which contains
the actual code that performs the
functions task.
The first line of the function definition is the
function header line.
That line contains the return type, function
name, and input parameter list.

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.

The C++ Hotel Example


There are three different rooms based
on the view.
The view of the beach costs $99.95
The view of the pool costs $79.95
The view of the parking lot costs $59.95

These rates are for a single room with


one person.
Each additional person is $10 per night.

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, );

These statements must be seen before


they are called. Here they are in the
source code above the main() function.

Six prototypes in the C++


Hotel program
No inputs no return value:
void WriteGreeting();

No inputs and return integers or a string


object.
int HowManyPeople();
int HowManyNights();
string WhatTypeRoom();

Three input values, 2 ints, 1 string, returns a


float.
float CalcCost(int people, int nights, string
roomType);

Four input values, no return value.


void WriteCostSummary(int people, int
nights,

RETURN STATEMENT

Describe the purpose and format of the 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;

It could be written like this:


return ((rate + addPersonCost)*
nights);

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";
}

Explain how functions access variables and parameters.

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);

Functions that have no


Inputs and No Return Value
When a function does not have any inputs,
nor does it return anything to the calling
function, the call statement is very simple.
The WriteGreeting() function is like this,
and must be called like so:
WriteGreeting()
;

Functions that have no


Inputs but have a Return
Value
When a function does not have any inputs,

but it does return a value, you have to be sure


the call statement has an assign operator so
that the returned value is placed in a variable.

Note how the input list parentheses are


empty, but the return values are each
assigned to one of mains variables.
numPeople = HowManyPeople();
numNights = HowManyNights();
roomType = WhatTypeRoom();

Functions that have input


and No Return Values
When a calling function must pass
information to the called function, but the
function doesnt return anything, the call
statement does not have an assign operator.
When this program writes the resultant cost
summary to the screen, this task is done by
the WriteCostSummary() function. The
function doesnt return any value to us.
WriteCostSummary(numPeople, numNights,
roomType,totalCost);

Functions that Input and


Return Values
When a calling function must pass
information to the called function, and
that function returns a value to us, we
need be have an assign statement to
obtain that value.
Here is the call to CalcCost(), which
returns to us the total cost of the stay.
totalCost = CalcCost(numPeople, numNights,
roomType);

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

Variables from main not available to HowManyPeople!


They are Out of scope

num

5Once HowManyPeople provides its value.


num goes out of scope!

le!
ariab
v
e
am
he s
Not t

num

3 Once HowManyNights provides its value.


num goes out of scope!

Explain how variable names are used in


functions.

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;
}

It doesnt matter the name of the variable being


passed and received, just the data type.

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

Functions have their own copies of the variables.


These variables are referred to as local variables.

sum

The result from adding 1 8 is 36

number

total

36
28
21
15
10
6
3
1

8
7
6
5
4
3
2
1

Explain how to troubleshoot functions.

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;
}

Explain the purpose of and how to overload functions.

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.

Saying Goodnight Four


Ways
Four different prototypes, same function
name, all write a goodnight message.
The function that is used depends on
what is passed to it.
void SayGoodnight();
void SayGoodnight(string name1);
void SayGoodnight(string name1, string
name2);
void SayGoodnight(int number);

Explain how to use and the purpose of default parameter


lists.

Default Parameter Lists

Default Input Parameter


List Functions
The default input parameter list allows
the program to declare a function that
has a variable number of input
parameters.
The programmer supplies the default
values for the inputs.
If the function is called and the values
are not passed to it, the function simply
uses the default values supplied in the
declaration.

Default Input Parameter


List Functions
The prototype for this type of function may or
may not contain the variable name, but the
default value must be supplied.
Default parameter list functions require the
programmer to pass inputs in the declaration
order.
Starting with the rightmost value, parameters
may be omitted from the call.
The function must be called with input values
starting on the left, and input values may not
be skipped.

Default Input Parameter


List Functions
In the DrawLines program, a default
parameter list is declared for a function
that prints lines of characters to the
screen.
The functions job is to draw a given
number of lines that are a certain
length, with a given symbol.
When the function is called, it needs to
know how many lines, what is the
symbol, and how many symbols on each
line.

Default Input Parameter


List Functions
We set up the default values:
a percent sign % for the symbol
twenty-five characters on a line
the default number of lines is one

The function prototype is:


void DrawLines(char symbol =
%,
int numOfSymbols = 25,
int numOfLines = 1 );

Default Input Parameter


List Functions
Call the function in the following four ways:
DrawLines();

//no inputs, default values are used

DrawLines(@, 30);
line

//use @, 30 chars, default 1

DrawLines(#,15,3);

//passing in all input values

DrawLines(%,6);
//vary the second value,
//must have the first

Output of the DrawLines


program.
Default Line 25 % on 1 line
%%%%%%%%%%%%%%%%%%%%%%%%%
Change to 30 @ on 1 line
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Now draw 15 # on 3 lines
###############
###############
###############
Last line has 6 % on 1 line
%%%%%%
No more lines for you.

Explain variable scope and how to use and purpose of local,


global and static variables.

Variable Scope

Local, Global and Static


Variables
Variable scope determines which
variables in the program are visible to
other portions of the program and
dictates how long a variable is
available while the program is
executing.
This variable visibility issue includes the
ability for one portion of the code to
access a variable in other parts of the
code.
The scope of the variable is determined
by the location where the variable is

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.

A program illustrating local


and global variables.
The name
variable is
global and all
functions can
see it.

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();

//Ask for the user's name

AskForAge(); //Ask for age


Write(); //Write information
return 0;
}

All functions in this


file can see these. No
need to pass between
functions

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);
}

Global Variables Are


Hazardous
Global variables should be used
sparingly and with considerable thought
as well as subsequent documentation.
As a general rule, global variables can
be used for mathematical constants or
universally used values and perhaps file
pointers or stream objects.
If the program is quite large, with many
user-written libraries, it is best to avoid
global declarations altogether.

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();

//keep a running total of the purchases


total = total + amount;
return total;
}

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.

Explain how to use the string stream class.

String Stream Class

The stringstream Class


The C++ stringstream class is a useful
class when working with string and
numeric data.
It is referred to as a stream object, and
is found with the C++ input/output
stream libraries.
You need to include the <sstream>
header when you want to use a
stringstream object.
Use the same formatting tools that we
use with the cout object with a
stringstream object.

The stringstream Class


When you need to write your program
data into a string in a formatted manner,
youll need to create a stringstream
object and place your data into that
object using the << operator.
Then use the str() function to assign the
contents into a string.
You can use all of the ios formatting
flags that we have for cout with a
stringstream object.

The stringstream Class


//Create a stringstream object.
stringstream ss;
// Variables well use for the string
double pi = 3.141592653589793;
float dollar = 1.00;
int dozen = 12;
//use our usual cout "tools with ss.
ss << " A dozen is " << dozen << ", a dollar is $";
ss.setf(ios::fixed);
ss.precision(2);
ss << dollar << " and \n";
ss << "the value of pi to 10
ss.precision(10);
ss << pi << ".";

places is ";

The stringstream Class


//now we assign the contents of ss into a string
//use the str() function.
text = ss.str();
cout << "\n Here is our formatted text string:\n"
<< text << endl;
//Add one more piece of data into the formatted
//string:
ss << "\n There are 2 \"+\"s in C++.";
text = ss.str();
cout << "\n Here is the final string: \n" << text <<
endl;

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++.

Describe common errors with functions.

Common Errors With Functions

Common Errors With


Functions
Compiler Error: function does not take __ parameters.

The function prototype and call statements do not match in the input lists.

Link Error: unresolved external: void _decl


Write(class string, int age)

The prototype, call statement and function header lines have to match.

Compile Error: missing function header


(old-style formal list?)

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

Você também pode gostar