0% found this document useful (0 votes)
6 views60 pages

8 CPP Functions

Presentation for C++ Functions

Uploaded by

drocsit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views60 pages

8 CPP Functions

Presentation for C++ Functions

Uploaded by

drocsit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Lecture 8: Functions

Harbin Institute of Technology ( Shenzhen )


School of Computer Science and Technology
Zhang Meishan ([email protected])
Copyright : Harbin Institute of Technology , Su Xiaohong , [email protected]
Overview
• Function
• Function arguments
• Parsing arguments
• Mathematical functions
• Function overloading
• Recursion
• The scope of a variable
8.1 Function
• A function is a block of statements called by name to carry out
a specific task
• In order to reduce the complexity of programs, they have to be
broken into smaller, less complex parts.
• Functions and classes are the building blocks of a C++ program.
8.1 Function
• Functions in the standard library: built-in, pre-written in C++

Line 11 calls the function sqrt() to


calculate the square root of the
value in the variable n
8.1 Function
• C++ allows a programmer to write functions ownly.

• Like variables, functions must be


declared before they are used.
• Line 7 declares stars to be a function
• The first void on line 7 declares the type
of the function stars()
• The second void informs the compiler
Return nothing Receive nothing that ‘stars’ will not receive any data from
the calling program. The second void is
optional.
-----prototype of the function stars()----
8.1 Function
• Program Example

Running Results

• Lines 22 to 26 define the function


• Line 22: function header
• Line 24- 25: function body
8.1 Function
To define and call a function with return
value, you should notice:
•function prototype
•function header
8.1 Function
• The general format of the return statement:

• Examples:

• These two blocks are equivalent:


8.1 Function
• A function call can be used anywhere in a program where
a variable can be used
8.2 Function arguments
• Function star() can display 11 asterisks, then how to display a
variable number of asterisks?
• New function stars():
take a value passed to it and display the number of asterisks
specified in that value.
8.2 Function arguments
• Program Example
Remark
•This number is called an argument
• Received by the parameter num
declared as an integer in line 23

Remark
•The parameters of a function are known
only within the function.
• Line 25 of the function stars() now
uses the variable num to decide how
many times * is displayed.
8.2 Function arguments
• A new program specifies:
• the number
• character to display
8.2 Function arguments

disp_chars() uses two parameters:


•num (the number of times to display a
character)
•ch (the character to display)

Return nothing
Receive an int and an char
8.2 Function arguments
• The variable names used in the prototype are often the same
as those used for the parameters in the function header.
• It is good practice to place comments after the function
prototype to describe the function and its parameters.
• The prototype and the accompanying comments are known as
the function interface.
8.2 Function arguments
• A function parameter that is not passed a value can be
assigned a default value.

•The second argument is omitted.


•These two are equivalent.

•If a parameter is provided


× with a default value, all the
√ parameters to its right must
also have a default value.
8.3 Passing arguments
• Passing by value
• A copy of the argument
values is passed to the
function parameters
• The value of the
argument cannot be A copy of the value of a
is passed to p
changed within the
function

Running Results
Changing the value of p has no effect on a
8.3 Passing arguments
• The value of the parameter can be prevented from change
within a function by making it a constant.
• To do this, place the keyword const before the parameter in the
function prototype and function header .
8.3 Passing arguments
• Passing by reference: A reference is a synonym or an alias for
an existing variable.
• A reference to a variable is defined by adding & after the variable’s
data type.
• r is a reference to n
• n and r both refer to the same
value
• A reference must always be initialized when it is• r defined
is not a copy of n, but is
merely another name for n
•A change to n will also result in
a change to r
8.3 Passing arguments
• Program Example

a and p refer to the same


storage location

Running Results

Changing the value of p also


changes the value of a
8.3 Passing arguments

Arguments passed by reference

local variable
•The variable temp is a local variable to the
function swap_vals().
•Local variables are known only within the
function where they are defined.
8.3 Passing arguments
• Arrays can only be passed by reference to a function.
• To avoid the overhead of copying all the elements of an array,
that passing by value would entail
• Program Example: contains a function sum_array() that sums the
elements of an integer array passed to it from main().
8.3 Passing arguments
•Line 16 calls sum_array() to calculate the
sum of the values in the array values.
•The arguments are the name and the
number of elements in the array.

•In line 20 array is a reference to values. Because arrays can


only be passed by reference, & is not required.
8.3 Passing arguments

•[ and ] are necessary to indicate that


the parameter is a reference to an
array.
• The number of elements is not
required in the brackets for a one-
dimensional array to handle different
size array.
•Const informs the compiler that
within the function sum_array(),
array is read-only and cannot be
modified.
8.3 Passing arguments
• an alternative way of commenting a function

•Instead of comments listing the parameters and return value, pre and
post condition comments are used.
•In the pre condition comment, the conditions that must exist before a
function may be successfully called are listed.
•In the post condition comment, the conditions that will exist after the
function is called are listed.

Call the function insert


8.3 Passing arguments
• When a multi-dimensional array is passed to a function,
the function parameter list must contain the size of each
dimension of the array, except the first.

Running Results
8.3 Passing arguments
• The elements of a two-dimensional array are stored row by
row in contiguous memory locations.

• Any element array[i][j] in this situation has an offset i*2 + j from


the starting memory location of array[0][0].

• In order to calculate the offset, the number of columns (= 2) is


required; hence the need for the compiler to know the value of
the second dimension
8.3 Passing arguments
• Passing a structure variable to a function
• pass a copy of the member values to that function, this means that
the values in the structure variable cannot be changed within the
function.
• The values in a structure variable can only be changed from within
a function if the variable is passed by reference to the function.
8.3 Passing arguments
• Program Example
•When a structure template is defined outside
main(), it makes the structure template global.
•This means that the structure template is known in
main() and in display_student_data() and
get_student_data().
8.3 Passing arguments
• Program Example
•demonstrates passing a
structure variable by value and
passing a structure variable by
reference to two different
functions.

•When a structure variable is


passed by value to a function,
the entire structure data must
be copied to the function
parameter.
•For a large structure, this is a
significant overhead and it is
preferable to use a reference.
•If the argument isn‘t changed
by the function, the const
keyword should be used.
8.3 Passing arguments
• The same considerations should be kept in mind when using
strings as arguments as when using structure variables as
arguments, i.e. passing a string by value means copying all the
characters of the string to a function parameter.
• To avoid this overhead it is preferable to pass strings by reference.
8.3 Passing arguments

demonstrates passing a C++


string by const reference to a
function that counts the
number of vowels in the string.

Running Results
8.3 Passing arguments
• To use C-strings instead of C++ strings in program, the
following modifications must be made to the program.
8.4 Mathematical functions
• To use any of the mathematical functions place the
statement #include <cmath> at the start of the program.
• Some trigonometric functions
8.4 Mathematical functions
• Program Example: demonstrates sin(), cos() and tan()
functions.
8.4 Mathematical functions
• Pseudo-random number functions
• To use the pseudo-random generating functions rand() and srand(),
place the statement #include <cstdlib> at the start of the program.
8.4 Mathematical functions
• Program Example •Line 12 assigns to t the current time
(measured in seconds since midnight on 1
January 1970, GMT) which is used as the
random number seed on line 14.
•Without line 14, the program displays the
same sequence of random numbers every
time the program is run.
8.5 Function overloading
• Function overloading is used when there is a need for two or
more functions to perform similar tasks, but where each
function requires a different number of arguments and/or
different argument data types.
8.5 Function overloading
• Using different functions with the same name in a program
is called function overloading and the functions are called
overloaded functions.
• Function overloading requires that each overloaded function have
a different parameter list, i.e. a different number of parameters or
at least one parameter with a different data type.
8.5 Function overloading
• Program Example

The compiler decides which of


the two sum_array() functions
to call based on matching
arguments with parameters.
8.5 Function overloading
• Program Example…continued

Running Results
8.6 Recursion
• Recursion is a programming technique in which a problem
can be defined in terms of itself. The technique involves
solving a problem by reducing the problem to smaller
versions of itself.
8.6 Recursion
• The factorial of a positive integer is the product of the
integers from 1 through to that number.

• (a) 0!=1. This is called the base case.


• (b) For a positive integer n, factorial n is n times the factorial of n-
1.This is called the general case clearly indicates that factorial is
defined in terms of itself.
8.6 Recursion
• Using the definition, factorial 3 is calculated as follows:
• The value of n is 3 so, using (b) above, 3! = 3 * 2!
• Next find 2! Here n = 2 so, using (b) again, 2! = 2 * 1!
• Next find 1! Here n = 1 so, using (b) again, 1! = 1 * 0!
• Next find 0! In this case using (a), 0! is defined as 1.
• Substituting for 0! gives 1! = 1 * 1 = 1.
• Substituting for 1! gives 2! = 2 * 1! = 2 * 1 = 2.
• Finally, substituting for 2! gives 3! = 3 * 2! = 3 * 2 = 6.
8.6 Recursion
• Program Example
8.6 Recursion
• Program Example

Note that
● Every recursive function must have at least
one base case which stops the recursion
● The general case eventually reduces to a
base case.
8.6 Recursion
• The factorial function could be written using iteration

•The recursive version will execute more


slowly than the iterative equivalent because
of the added overhead of the function calls.
•The advantage of the recursive version is
that it is clearer because it follows the actual
mathematical definition of factorial.
8.7 The scope of a variable
• The scope of a variable refers to the part of the program in
which a variable can be accessed.
• block scope
• global scope
• Block scope
• A block is one or more statements enclosed in braces { and } that
also includes variable declarations.
• A variable declared in a block is accessible only within that
block.
8.7 The scope of a variable
• Block scope

The scope of the variable f


8.7 The scope of a variable
continued

The scope of the variable x , y


8.7 The scope of a variable
continued

The scope of the variable z


8.7 The scope of a variable
• Variables declared inside the parentheses of a for are
accessible within the parentheses, as well as in the
statement(s) contained in the for loop.
8.7 The scope of a variable
• Global scope
• A variable declared outside main() is accessible from anywhere
within the program and is known as a global variable.
8.7 The scope of a variable
• Global scope
• A variable declared outside main() is accessible from anywhere
within the program and is known as a global variable.

•Because global variables are known, and


therefore can be modified, within every function,
they can make a program difficult to debug and
maintain.
•Global variables are not a substitute for function
arguments. Apart from its own local variables, a
function should have access only to the data
specified in the function parameter list.
8.7 The scope of a variable
• Reusing a variable name
• It is permissible to give a variable the same name as another variable
in another block. This is known as name reuse.

If a variable is declared in an inner block and if


a variable with the same name is declared in a
surrounding block, the variable in the inner
block hides the variable of the surrounding
block.
8.7 The scope of a variable
• Reusing a variable name
• It is permissible to give a variable the same name as another variable
in another block. This is known as name reuse.

If a global variable is hidden by a local


variable, the global variable can still be
accessed using the unary scope resolution
operator ::

Q&A
ZhangMei
Shan

56/37
Homework
• 1. What is wrong with each of the following functions?
Homework
• 2. What is the output from the following?
Homework
• 3. What is the output from the following?
Homework
• 4. (a) Write a function to return the minimum value in an
integer array. (b) Overload the function in (a) with a
function to return the minimum value in a floating-point
array.
• 5. What does this recursive function do?

You might also like