Sxith Laboratory Session - Functions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

Functions in C++

Agenda
• What is a function?
• Sharing data among functions
• Types of C++ functions: through function parameters
• Standard functions • Value parameters
• User-defined functions • Reference parameters
• C++ function structure • Const reference parameters
• Function signature • Scope of variables
• Function body • Local Variables
• Declaring and • Global variable
Implementing C++
functions

2
Functions and subprograms
• A function is a group of statements that together perform a task.
• Every C++ program has at least one function, which is main(), and all
the most trivial programs can define additional functions.
• You can divide up your code into separate functions.
• How you divide up your code among different functions is up to you,
but logically the division usually is such that each function performs a
specific task.

3
C++ Standard Functions
• C++ language is shipped with a lot of functions which are known as
standard functions
• These standard functions are groups in different libraries which can
be included in the C++ program, e.g.
• Math functions are declared in <math.h> library
• Character-manipulation functions are declared in <ctype.h> library
• C++ is shipped with more than 100 standard libraries, some of them are very
popular such as <iostream.h> and <stdlib.h>, others are very specific to
certain hardware platform, e.g. <limits.h> and <largeInt.h>

4
User-Defined C++ Functions
• Although C++ is shipped with a lot of standard functions, these
functions are not enough for all users, therefore, C++ provides its
users with a way to define their own functions (or user-defined
function)
• For example, the <math.h> library does not include a standard
function that allows users to round a real number to the ith digits,
therefore, we must declare and implement this function ourselves

5
How to define a C++ Function?
• Generally speaking, we define a C++ function in two steps (preferably
but not mandatory)
• Step #1 – declare the function signature in either a header file (.h file) or
before the main function of the program
• Step #2 – Implement the function in either an implementation file (.cpp) or
after the main function

6
What is The Syntactic Structure of a C++ Function?
• A C++ function consists of two parts
• The function header, and
• The function body
• The function header has the following syntax
<return value> <name> (<parameter list>)
• The function body is simply a C++ code enclosed between { }

7
Example of User-defined
C++ Function

double computeTax(double income)


{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}

8
Example of User-defined
C++ Function
Function
header

double computeTax(double income)


{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}

9
Example of User-defined
C++ Function
Function Function
header body

double computeTax(double income)


{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}

10
Function Signature
• The function signature is actually similar to the function header
except in two aspects:
• The parameters’ names may not be specified in the function signature
• The function signature must be ended by a semicolon
Unnamed Semicolon
• Example Parameter ;

double computeTaxes(double) ;

11
First Function Example
Functions
• This program is divided in two functions: addition and main.
• Remember that no matter the order in which they are defined, a C++
program always starts by calling main.
• In fact, main is the only function called automatically, and the code in
any other function is only executed if its function is called from main
(directly or indirectly).
Functions
• In the example above, main begins by declaring the variable z of
type int, and right after that, it performs the first function call: it
calls addition.
• The call to a function follows a structure very similar to its
declaration.
• In the example above, the call to addition can be compared to its
definition just a few lines earlier:
Functions
• The parameters in the function declaration have a clear
correspondence to the arguments passed in the function call.
• The call passes two values, 5 and 3, to the function; these correspond
to the parameters a and b, declared for function addition.
• At the point at which the function is called from within main, the
control is passed to function addition: here, execution of main is
stopped, and will only resume once the addition function ends.
Functions
• At the moment of the function call, the value of both arguments (5
and 3) are copied to the local variables int a and int b within the
function.
• Then, inside addition, another local variable is declared (int r), and
by means of the expression r=a+b, the result of a plus b is assigned
to r; which, for this case, where a is 5 and b is 3, means that 8 is
assigned to r.
Functions
• The final statement within the function: return r;
• Ends function addition, and returns the control back to the point
where the function was called; in this case: to function main.
• At this precise moment, the program resumes its course on main
returning exactly at the same point at which it was interrupted by the
call to addition.
• But additionally, because addition has a return type, the call is
evaluated as having a value, and this value is the value specified in the
return statement that ended addition: in this particular case, the
value of the local variable r, which at the moment of the return
statement had a value of 8.
Functions

•A function can be called multiple times


within a program, and its argument is
naturally not limited just to literals: - see
next slide.
Functions
Functions with no type: The use of void
• But what if the function does not need to return a value?
• In this case, the type to be used is void, which is a special type to
represent the absence of value.
• For example, a function that simply prints a message may not need to
return any value:
Functions with no type: The use of void
• In C++, an empty parameter list can be used instead of void with
same meaning, but the use of void in the argument list was
popularized by the C language, where this is a requirement.
• Something that in no case is optional are the parentheses that follow
the function name, neither in its declaration nor when calling it.
• And even when the function takes no parameters, at least an empty
pair of parentheses shall always be appended to the function name.
Functions with no type: The use of void
• See how printmessage was called in an earlier example:
• printmessage ();
• The parentheses are what differentiate functions from other kinds of
declarations or statements.
• The following would not call the function:
• printmessage;
Return of Main
• You may have noticed that the return type of main is int, but most
examples in this and earlier chapters did not actually return any value
from main.
• Well, there is a catch: If the execution of main ends normally without
encountering a return statement the compiler assumes the function
ends with an implicit return statement:
• return 0;
• Note that this only applies to function main for historical reasons.
• All other functions with a return type shall end with a proper return
statement that includes a return value, even if this is never used.
Arguments passed by value and by reference
• In the functions seen earlier, arguments have always been passed by
value.
• This means that, when calling a function, what is passed to the
function are the values of these arguments on the moment of the
call, which are copied into the variables represented by the function
parameters.
• For example, take
• int x=5, y=3, z;
• z = addition ( x, y )
Arguments passed by value and by reference
• In this case, function addition is passed 5 and 3, which are copies of
the values of x and y, respectively.
• These values (5 and 3) are used to initialize the variables set as
parameters in the function's definition, but any modification of these
variables within the function has no effect on the values of the
variables x and y outside it, because x and y were themselves not
passed to the function on the call, but only copies of their values at
that moment.
Arguments passed by value and by reference
• In certain cases, though, it may be useful to access an external
variable from within a function.
• To do that, arguments can be passed by reference, instead of by
value.
• For example, the function duplicate in this code duplicates the value
of its three arguments, causing the variables used as arguments to
actually be modified by the call: (See code)
Arguments passed by value and by reference
• To gain access to its arguments, the function declares its parameters
as references.
• In C++, references are indicated with an ampersand (&) following the
parameter type, as in the parameters taken by duplicate in the
example above.
• When a variable is passed by reference, what is passed is no longer a
copy, but the variable itself, the variable identified by the function
parameter, becomes somehow associated with the argument passed
to the function, and any modification on their corresponding local
variables within the function are reflected in the variables passed as
arguments in the call.
Arguments passed by value and by reference
• In fact, a, b, and c become aliases of the arguments passed on the
function call (x, y, and z) and any change on a within the function is
actually modifying variable x outside the function.
• Any change on b modifies y, and any change on c modifies z.
• That is why when, in the example, function duplicate modifies the
values of variables a, b, and c, the values of x, y, and z are affected.
Arguments passed by value and by reference
• If instead of defining duplicate as:
• void duplicate (int& a, int& b, int& c)
• Was it to be defined without the ampersand signs as:
• void duplicate (int a, int b, int c)
• The variables would not be passed by reference, but by value,
creating instead copies of their values.
• In this case, the output of the program would have been the values of
x, y, and z without being modified (i.e., 1, 3, and 7).
Declaring functions
• The prototype of a function can be declared without actually defining
the function completely, giving just enough details to allow the types
involved in a function call to be known.
• Naturally, the function shall be defined somewhere else, like later in
the code.
• But at least, once declared like this, it can already be called.
Recursivity
• Recursivity is the property that functions have to be called by
themselves. It is useful for some tasks, such as sorting elements, or
calculating the factorial of numbers.
• For example, in order to obtain the factorial of a number (n!) the
mathematical formula would be: n! = N*(n-1)*(n-2)*(n-3)….* 1
• Therefore 5! Would be 5! = 5*4*3*2*1 = 120
Program to compute Factorial Using
Recursion
Defining a Function
• A C++ function consists of two parts
• The function header, and
• The function body
• The function header has the following syntax
return_type function_name( parameter list )
{
body of the function
}
Defining a Function (Parts of a function)
• Return Type
• A function may return a value.
• The return_type is the data type of the value the function returns.
• Some functions perform the desired operations without returning a value.
• In this case, the return_type is the keyword void.
• Function Name
• This is the actual name of the function.
• The function name and the parameter list together constitute the function
signature.
Defining a Function (Parts of a function)
• Parameters
• A parameter is like a placeholder.
• When a function is invoked, you pass a value to the parameter.
• This value is referred to as actual parameter or argument.
• The parameter list refers to the type, order, and number of the parameters of
a function.
• Parameters are optional; that is, a function may contain no parameters.
• Function Body
• The function body contains a collection of statements that define what the
function does.

You might also like