Vous êtes sur la page 1sur 15

CHAPTER ONE depending on whether they return values or not, C++

FUNCTIONS functions can be categorized into value retuning functions


Introduction and void functions. The return type for value returning
C++ programs are a collections of functions. Functions functions is the same as the data type of the value which
are entities in C++ programs which are used to write is returned by the function. This can be int, double, float,
statements. You may have declarations without functions. char, String, short, long. If a function doesnt return a
However, you cant make a C++ program to execute value, its return type will be void. Mentioning the return
certain statements unless you have a function. For type while defining a function is optional. However, if
instance, the following C++ program is intended to there is no return type which is explicitly stated, the C++
display the sum of two numbers. But, the result will not program assumes the return type is int. While defining
be displayed since the program doesnt have the entity functions, the return type is stated in front of the function
where you can write C++ statements. In short, since the name.
program doesnt have a function, you cant get outputs.
Parameters (or arguments). A function may use inputs
Program 1.1[Incorrect].cpp to execute the statements in the body. For instance, if the
task of a certain function is to give the sum of two
numbers which are passed to it, the function needs to take
those values which will be added as an input to give their
sum. Those input which are passed to a function are called
parameters or arguments. Since the closed brackets are
the gateway to the function, the parameters are passed to
the function through the closed brackets. The number of
parameters which a function can take is not limited to
Thus, in C++ program, you need to define functions to only one parameter. You can pass a number of parameters
write statements and to get results. with different data type to a function. If a function takes
parameters, the data type of the parameters should also
Defining Functions be stated. Otherwise, the program will assume that the
If you understand the importance of functions, the next
data type is an integer.
question will be how functions are defined in a C++
program. To define functions, you need three mandatory Return statement. If a function returns a value, there
and three optional components. The mandatory should be a return statement in the function. The return
components of a function are function name, closed statement should be the last statement in the function. A
brackets, and closed braces where are the optional return statement has two components. The first
components are return type, parameters (or arguments) component is the return word. The other component is
and return statement. These components will be the value which is returned. The value which is returned
discussed as bellows. may be an expression but should match the return type.
Function name. Every function in a C++ program A complete C++ function definition for value returning
should have its own name. The name can be any functions is shown below.
combination of characters provided that the function
name is not among the reserved C++ words, nor it
doesnt begin with numbers, nor it doesnt contain some
reserved C++ characters.
Closed Brackets. The function name should be followed
A complete C++ function definition for void functions is
by closed brackets. These brackets will serve as a gateway
shown below.
to the function.
Closed Braces. The closed braces should be written next
to the closed brackets. They are used to contain the body
of the function.
Return Type. C++ functions may just execute certain
statements without returning a value or they may return The function name and the parameter lists are together
some values to the entity which called them. Thus, called signature of a function. The signature doesnt

By: Asaye Chemeda Email: asayechemeda@yahoo.com 1


include the return type. A signature of a typical C++ it fulfills the two conditions that a program should at least
function is shown below. has one function and that any C++ program should have
main function.

At this point, you are convinced that, any C++ program


should have a function in order to execute statements.
Thus, having function is a necessary condition to execute
statements in C++. One question may be raised here: is
having a function a sufficient condition for C++
programs to be executed? Let us have a look at the
following program which is intended to display Hello
World! on the console.
When the above program is run, the function body
Program 1.2 [Unexecuted].cpp between the braces (the cout statement) will be executed
and the Hello World! message will be displayed.
The function body may contain any number of statements
and you can put every statement which is required to
perform a certain programming task inside the main
function body. If so, what is the importance of defining
other functions than main function? There are two
This program fulfils the conditions that functions are reasons for this. The first one is that some programs may
required to execute statements. It has return type (void), require several lines of codes and it may be unwise to put
a function name (helloWorld), the closed brackets, the all the code in only the main function. Thus, you will
closed braces and the function body (the cout divide the code into a number of manageable pieces and
statement). If you run the above program, will it display you will put them in different functions. For instance,
the message Hello World! on the console? The answer assume you want to write a C++ program to build a
is no. The above program lacks one thing which every simple calculator. This requires building the user
C++ should have - which is the main function. If you interface, taking values which will be added or multiplied
want to execute statements in C++, the program must or any other operation to be done on, calculating the
have a main function. result of the operation and displaying the results. If a
program for a simple calculator has all these tasks, each
The main function with a number of lines of codes, why do put all the code
A C++ program will not be executed unless it has a main in the main statement? It is unmanageable. For instance,
function. One important thing to note here is that the if you want to improve any of the above tasks you have
main function is always the function where a program to go through the whole main function. The best way to
starts execution. The main function has a function name avoid this is to have different functions performing
of the word main and a return type of int. The main manageable pieces of codes.
function returns a value of int data type to the operating
system. By convention, the return value 0 is used to The second reason to have other functions than main is
indicate the program is executed successfully and other to avoid repetition of codes. For instance, in the simple
integer values indicating the opposite. The main function calculator program mentioned above, the way in which
may or may not take arguments. When the main function the output is displayed may be the same whether you
takes arguments, the arguments are two. The first added or multiplied two numbers. So, why do you write
argument is an integer while the second one is a point to separate statements for displaying results for the addition
an array of character pointers. Thus, the signature of the and multiplication? Isnt it better if you have only one
main function may have one of the following two types. output display function which can be accessed by all the
operations? Doesnt this avoid repetition of many lines of
codes? Doesnt this save time, which is a very important
factor if you are a programmed with many projects? If so,
If a C++ program has main function, it will be executed. you will definitely agree that other functions than main
Program 1.2 can now display the Hello World! message may be necessary to attain the above two benefits
if it is corrected to Program 1.3 which is shown below as breaking the code into manageable pieces and avoiding
repetition of codes.
By: Asaye Chemeda Email: asayechemeda@yahoo.com 2
When a program has more than one function, how do the program. This line of the function returns the sum of any
functions interact with one another? If one function two double type values which are passed to the function
wants to interact with another, it calls the other function. as arguments. One this to note here is that, in the return
This may be for one or a combination of the following statement, you can write expressions after the return
three reasons. A function may call another function to get word.
a certain result or to change the value of some variable or
to print (or display) something. Whichever reason it is, if The main function has an int return type and takes no
a function wants to call another function, it just writes the arguments. The body of the function, the part of the
signature of the function without the data type of the function within the braces, starts with defining statement
arguments at the place where it wants to interact with the of three variables a, b and c which are of double data
other function. When you write the signature of certain type. This is the first statement which will be executed in
function, it means that you are interacting with that the program as execution of statements in C++ programs
function. from the main function. The next statement is taking the
values of a and b respectively as an input from the
You may ask, are there any rules when functions interact console by using cin. Line 13 of the program is the place
with one another? The answer is yes. One of the rules is where the main function interacts with the add
the called function should be written before the calling function. In this line the value c is assigned with the
function or there should be a prototype of the called signature of the add function. Since the add function
function before the calling function. Before looking into returns the sum of two double values which are passed to
the details of this rule, let us understand which one the it and since on the signature of the add function on line
called function is and which one the calling function is. 13, the values or a and b are passed, the value of c will
This will be illustrated with the following program. be assigned with the return value the add function. In
Program 1.4[Correct].cpp other words, on line 13, the main function has called the
add function to assign the value of c with the sum of a
and b. Thus, the main function is the calling function
as it is calling another function and the add function is
the called function as it is called by another function.
If you run the above program, you will be prompted to
enter two values on the console and their sum will be
displayed after entering the second number.
Now, any doubts regarding the calling and the called
function are cleared and let us proceed to the details of
the rule mentioned above. Before that, try to run Program
1.4 by placing all the components of the add function
after the main function. Did you get the result which you
expected? Did the program even pass the compilation?
The answer is no. Mind you, you just only place the add
The above program is intended to print the sum of two function after the main function and you didnt remove
values which are entered from the console. In the or add anything to the existing functioning program. So,
program, there are two functions: the mandatory main why is the program not free of compilation errors? If you
function and the add function. The return type of the remember the rule, it says you cant put the called function
add function is double and having a return statement is after the calling function unless there is a prototype of the
mandatory for this function. The function takes any two called function before the calling function. There is a
arguments which are of double data type. Thus, compilation error now because the called function (add)
whenever it is desired to interact with this function, the is placed after the calling function (main) and there is no
function name (add) must be explicitly stated and two prototype of the called function (add) before the calling
double values separated by a coma should be passed as function (main). If there are more than one interacting
arguments between closed brackets. The identifiers used functions, there are two available options for having a
for the arguments (a and b) may not be the same as the working program. The first option is to place the called
identifiers which is defined in the function which wants function before the calling function.
to interact with this function. The required return
statement for this function is stated on line 6 of the
By: Asaye Chemeda Email: asayechemeda@yahoo.com 3
The second option is to put the prototype of the called Program 1.5 can be compiled without any errors even if
function before the calling function and you can put the the called function (add) is placed after the calling
called function after the calling function. The first option function (main). This is because the prototype of the
may sometimes create ambiguities for the person who add function is placed before the main function on line
came up in dealing with a program written by another 5. In the prototype of the function on line 5, the return
person as it often happens in programming work places. type, the function name and the data type of the
Imagine you are dealing with a program written by arguments match to that of the actual add function given
another person. What you normally do is you will go in line 16 as it should be. In the prototype, the identifiers
through the program from the top to down and if the of the arguments are omitted as any identifier can be used.
program is written by the first of the above mentioned
two options, you will first encounter the called functions, Let us try to add one additional function to Program 1.5.
which can be several of them, and you dont know when The task of this function will be displaying a message that
and why they are called. So, you will get confused. To says the sum of a and b is c. The name of the function
avoid this, the second option is frequently used in will be printSum and it will not return any value, it just
programming community. As mentioned earlier, the prints. As a result it should be of void return type. The
second option requires putting the prototype of the called function will replace line 12 of Program 1.5. Thus, the
function before the calling function. This is called printSum function will be called from line 12 of the
prototyping. So, what prototyping is and how it is done main function. Since a, b, and c are defined in the main
will be the next topic. function and since this function doesnt make any
calculations, why should this function take any
Function Prototyping arguments? If you say so, the function will be defined with
Function prototyping is declaring a function without empty parameters. Of course, dont forget to put either
including the body of the function. Thus, a function the function or the prototype before the calling function.
prototype includes the return type of the function, the Now the program appears to be:
function name and the argument lists. A function
prototype ends with a semi-colon like other C++ Program 1.6[Incorrect].cpp
statements. When a functions is declared by prototyping,
the identifiers used for the arguments are dummy
variables (can take any appropriate variable identifier) and
they can be omitted. A complete function prototype will
have one of the following forms without any change in
the outcome.

Program 1.4 can now be modified to the following


program without any change in the outcome of the
program.
Program 1.5[Correct].cpp
In this program, a new function printSum is defined
and it is called from line 12 of the main function. Now,
try to compile the program and see if there are any errors.
Of course there are. Specifically on line 21 of the program.
Oh, did I forget to put the prototype before the calling
function? No! It is already on line 6. Did I miss any semi-
colon? No! Then, why are the errors occurring although
the program seems faultless. The errors occurred due to a
concept known as scope in C++.
Scope of Variables
Scope means the limit which a piece of code at one place
of the program has in order to access and use a piece of
code at another place. In C++, variables which are
defined inside a function can only be accessed and used
By: Asaye Chemeda Email: asayechemeda@yahoo.com 4
by a code inside that function. Thus, the scope of the which is defined as x in the printSum function (but
variables declared inside a function is only within the which can be defined as any name in the calling function)
function itself. Note that there may be exception to this and second argument which is defined as y in the
rule and that exception will not be dealt in this chapter. printSum function (but which can be defined as any
Variables which are defined within a method and which name in the calling function) is third argument which is
have a scope within the function itself are termed as local defined as z in the printSum function (but which can
variables. There are also variables which are defined be defined as any name in the calling function). So, when
outside functions. The scope of these variables is not you pass arguments to another function, the name of the
limited to any function and such variables can be accessed arguments dont matter. It is their order which matters.
from anywhere within a given program. These type of To understand this, let us have a close look at line 12 and
variables are termed as global variables. line 20 of the program. These lines are extracted and put
as follows:
At this point, what you have to note is, unless additional
key words are used, the scope of a variable defined in a
function is within the function itself. Which means that
the add function cannot directly access and use the
When a call to the printSum function is made on line
variables a,b and c in the main function and the same is
12, the first place where the call goes to is the prototype
true for the printSum function. I see! Apparently, the
on line 6. The prototype checks whether the data type of
printSum function which dared to print a message that
the arguments passed on line 12 actually match those
the sum of a and b is c cant actually access neither of
stated in the printSum function. If the matching is
these variables. Now, you understand what line 21 of
successful, the call goes to the implemented function
Program 1.6 was trying to do. It was just like printing an
which is on line 20 of the code. At this point, the
undefined variable c which is presumed to be the sum of
printSum function will assign its variables (x,y and z)
two undefined numbers a and b. Can you use variables
with the corresponding variables in the call. For instance,
without defining them in C++? Of course not! That is the first argument in the call (line 12) is a and the
why the error occurred. What could be a solution for this?
printSum function will assign the first variable in its
There are a number of solutions and one of them is to
argument list (x) by a. The same is true for the other
pass the variables a,b and c to the printSum function
arguments. In other words, the first thing which
as arguments. The following program will be perform the
printSum function does is implicitly assigning its
intended task in program 1.6 without any compilation
arguments as follows:
errors.
Program 1.7[Correct].cpp

As a result, even if the variable names used in the calling


and the called function are different, the outcome will be
the same. Try to switch the places of a, b and c on line
12 and see the printed message.
At this point, you understand that one way to grant access
for other function to use variables defined in a given class
is by passing them as arguments. Now, let us have more
fun by writing another program and let us grab a new
concept. The program which we are going to write takes
two values a and b from the console and swaps the values
Note the changes on line 6, line 12 and line 21. Another of a and b and prints the swapped values. The variables
thing to note is when the main function calls the will be defined and their values will be read in the main
printSum function on line 12, it passed a,b and c function while the swapping will be done by another
respectively as arguments but the printSum function function. Let use call the function swap. But, C++
accepted x,y and z respectively as arguments. This already has a built-in function called swap which
doesnt have any problem. Because, what the printSum performs a similar task to what we are going to do. By the
function does is printing the sum of the first argument way, C++ has several built in functions which perform

By: Asaye Chemeda Email: asayechemeda@yahoo.com 5


some specific tasks which can be used at the users swapValues function does, has no reference to the
convenience. Nice! This simplifies your job as a main function. This is called passing parameters by
programmer since you dont have to write everything to values. If a calling function passed parameters to the
write a functioning program. Let us get back to our called function by value, then the called function cannot
program and to avoid any confusion let us give a name of change the original values of the parameters in the calling
swapValues for our function. The values of a and b function.
will be passed to the swapValues function as
Now, you have got the clue why the values of a and b
arguments in order to grant access for this function to use
the variables. The swapValues function just swaps the were not swapped. Even if the swapValues function
values of a and b without returning any value. Hence, its swapped the values of the arguments which are passed to
return type will be void. Here is the program: it, it doesnt actually swap the original values in the main
function. The swapping only remains in the
Program 1.8[CannotSwap].cpp swapValues function. This is because the values are
passed by values. Can we do anything to change the values
of parameters in a calling function from a called function?
Of course, we can! C++ has the facility to do this. It is
called passing by reference or calling a function by
reference.
Call by Reference
C++ has a facility in which two identifiers can be used to
refer to the same variable. Such variables are termed as
reference variables. To create a reference variable, an
original variable should be first defined. The reference
variable and the original variable refer to the same data
object in the memory. The C++ syntax used for creating
In the above program, the swapValues function takes reference variable is as follows.
two values of double data type and swaps their values i.e.
it gives the value of a to b and the value of b to a.
Another variable x is also defined to take the original To understand how reference variables work, look at the
value of a so as not to lose the value of a in the process following program.
when the value of b is assigned to a. In the main
Program 1.9[Correct].cpp
function, there are two cout statements. The first one
displays the values of a and b before swapping. The
second cout statement comes after the swapValues
function is called. Thus, it is expected that the values
printed by this statement will be the reverse of the first
cout statement. For instance, if you enter the value of a
as 1 and the value of b as 2, you will expect that the first
cout statement prints 1 and 2 and the second
cout statement prints 2 and 1. Run the program
and see the result. Did you get the result which you
expected? Surely not! Check the swap function again. Isnt
In the above program, a variable named a was defined on
it swapping the values of the arguments which are passed
to it? Of course it does! So, where did it go wrong? line 6 and it was initialized with a value of 10. On line 7, a
reference variable to a was defined as b. Note the &
Apparently, there is nothing wrong with the program. operator which was used while defining b. On line 8, the
But, one detail is missing. When you passed the value of value of b was doubled. On line 9, the value of a was
a and b (which are defined in the main function) to the printed. What do you think will the displayed value be? If
swapValues function, you just passed the values of the you are not familiar with reference variables, your answer
variables to the function. Again, when the swapValues will be 10. You are reasonable to say so because there is
function accepted the values of a and b, it just accepted no any statement which directly changes the value of a.
the values of the variables. In such cases, whatever the Run the program and see the result. It is 20. How come?

By: Asaye Chemeda Email: asayechemeda@yahoo.com 6


This is because after b is defined as a reference variable swap the original values in the main function. To
to a on line 7, both variables (a and b) refer to the same understand this better, go back to Program 1.7 and revise
memory location. As a result, whatever operation you what we said about how the called function creates its
perform on either of them, the other one will also pass own new variables and assigns the values of these
through the same operation. If you double the value of b, variables with those of the calling function according to
the value of a will also be doubled automatically. Since their sequence. There will be no reference made to the
the value of the reference variable (b) is doubled on line calling function variable. Thus, if a value is passed to the
8, the value of the original value (a) will also be doubled. called function, the changes which are made in the called
You will also get the same result if you double the value function will remain in the called function. Even if you
of a and print the value of b. Now, it is pretty clear what define reference variables in the swapValues function,
reference variables are. the defined reference variables will refer only to the new
variables which are defined in the signature of the
After understanding the concept of reference variables, function; not to the values in the calling function. As a
did you get any idea on how you can alter the value of result, the second option is not feasible.
variables in the calling function from the called function?
Remember, if you define a reference variable to a variable, Let us see the third option. If you understand, the
you can alter the value of the original variable by altering drawback of the second option, it is easy to guess what
the value of the reference variable. If so, to alter the value the third option might be. The main drawback of the
a variable in a calling function from the called function, second option is that, the called function will not have
why dont you define a reference variable in the called control over the calling function variables once they
function referring to the original variable in the calling passed the gateway into the body of the function. What
function? Will there be any problem if you try do so? can we do then? To answer what we could do, once again
There might be. The problem is the called function should refer back to Program 1.7. Specifically, note how the
get access to the original variables in the calling function. called function implicitly assigns its variables in the
Of course, you know the solution for this problem. The argument list with the variables passed to it. This one
solution is you can pass the variables as arguments. Right? concept. Also, refer back to how reference variables are
Now, you understand the framework about how variables defined. Another concept! Do you see a common point
in the calling function can be altered from the called in these two concepts? Of course you do. What if you
function. Let us go to the details. define a reference variable to the calling function on the
signature of the called function itself? Doesnt this solve
First, let us see the available options in which a reference all of our problems which we had?
variable in the called function is created and their
feasibility. For this, we will refer back Program 1.8. To Defining a reference variable on the signature of the called
define a reference variable to a and b in the function to the original variables in the calling function
swapValues functions, there are three options. will make it possible to alter the values of the variables in
the calling function from the called function. This is what
The first option is if we can call the swapValues is called passing by reference or calling a function by
function from the line 11 of the main function as below: reference. Now, Program 1.8 can be modified as follows.
Note that changes are made only on line 5 and line 16 of
program 1.8.
This is possible. But, understanding the detail requires a Program 1.10[Correct].cpp
concept which will be discussed in chapter three.
Therefore, we will skip this option for the time being.
The second option is the pass the values of the original
variables when the swapValues function is called in
the main function. This means, line 11 of the program will
not be changed. Again when the swapValues function
takes the variable from the main function, let it take the
actual values of the variables. Then, in the swapValues
function, let us define reference variables to a and b and
let us swap their values. What do you think of this second
option? It is just like back to square one. Right? Because,
this is no different from the Program 1.8, which failed to
By: Asaye Chemeda Email: asayechemeda@yahoo.com 7
What this program does which is different from program Isnt this reference concept interesting? Indeed it is! But,
1.8 is that the swapValues function defines reference have we covered what we have to know regarding
variables of the original variables in the main function in reference at least for this chapter? A little more remains.
its signature. As a result, the variables in the main
A function can take reference of another variable as
function and in the swapValues function refer to the
arguments. This enables a function to alter the values of
same memory location. Therefore, whatever the
the variables to which the reference is made. Interesting!
swapValues function does to its arguments, the
Let us think both ways and ask this question: is it possible
changes will persist to the original variables in the main
to get reference of the variables returned by a function?
function. When the arguments of the swapValues is
Thanks to the C++ developers, the answer is yes. If you
changed, its prototype on line 5 should also be changed. think of the potential effects of this possibility, you will
Now, run the program and see the result. Now, when the realize that C++ program is indeed versatile. If a function
values of a and b are printed before and after calling the returns values which you cant have reference, then the
swapValues function, they are actually swapped. function is returning by value. You can also have
The advantage of passing by reference is three fold. The reference to what is returned by a function. This is the
first one is to alter values of variables from an outside concept which has to be covered before concluding the
function. The second one is to return more than one reference concept for this chapter.
variable from a function. Value returning functions return Return by Reference
only one value through their return statements. However, If a function returns the reference the return value, the
if calling by reference approach is used, a function can function is said to be returning by reference. At this
return more than one value. In Program 1.10, the program point, you are expected to know how reference variables
actually returned two values the swapped values of a are defined. It was easy, right? If you have any doubt, go
and b. The third advantage of passing by reference is through the topic of calling by reference. That is how
saving memory space. Since the original variables and the things work, if you want to be good at programming, you
reference variables refer to the same memory location, a will deal with it till you understand it completely. No
lot of memory space which could have been wasted by giving up!
defining two separate variables in each of the functions
can be saved. To understand the concept of return by reference, we will
try to solve one mathematical problem. Are you expecting
Let us raise an interesting question here based on the some calculations? Not really. We will just write a
three advantages of passing by reference. Say, within a program to solve it. The problem is as follows. Assume in
program, you want to save memory by using pass by a certain mathematical problem, the value of a certain
reference but you want to restrict any changes to the variable can have a value from 0 up to 3 only. If part of
reference variable. Can we do this in C++? The answer is the calculation results in a value to the variable outside
yes. What we need to do is put a qualifier const before this range, the variable takes the maximum value, i.e. 3. If
the data type of the reference variable in the argument list the variable is x and you express it with a mathematical
of the function and in the prototype. However, when you equation, it appear like:
add the qualifier const in front of the data type of a
||  || 3
reference variable any attempt to change it, will result in =
compilation error. 3 || > 3

For instance, you can change the signature, and of course What we are going to do next is writing a program which
the prototype, of the swapValues function in Program gives the value of x for any value entered from the
1.10 as follows. console. C++ has built-in absolute value function, but we
will write our own absolute value function since it is very
easy. The absolute value function which we are going to
define will have a function name of abs. Just to recall
This restricts any change to reference variable a (and
what an absolute value function will do, it gives the value
therefore the original variable a in the main function)
of the number if the number is positive or zero or the
within the function. When you try to run the program you
negative of the number if the number is negative. As the
will get an error message on line 18. Because on that line
negative of a negative number is positive, you will always
you tried to change the value of the reference variable.
have a positive value of a number after passing through
the absolute value function. The program is given below.

By: Asaye Chemeda Email: asayechemeda@yahoo.com 8


Program 1.11[Correct].cpp or reference variable. Since the only reference variable in
the abs function to the x variable in the main function
is value, the value of x will be changed only when the
value of the value variable is changed. In the abs
function, the value variable is assigned with a new value
only on line 11. If this line of the program is removed,
then there will be no change to the value variable and
there will be no change to the x variable either.
Here comes the question which is relevant to this topic.
Can you change the value of the value variable from the
main function? Not directly, but you can. If you want a
local variable to be changed outside the function return
that local variable and make the function to return by
reference. Do you know the reason why you cant directly
In the above program, a global variable absValue is change the value variable from the abs function? It is
defined on line 4. Who can access this variable then? because of scope issue. The value variable is a local
Every piece of code in the program can access this variable and it cannot be accessed from outside of the
variable. Because the scope of global variables is not abs function. And since the value variable is not the
limited to any function or any piece of code. The abs return value of the abs function, you cannot change its
function is placed before the calling main function. Do value at all from outside the function even if you make
you have to define a prototype for the abs function? Of the function to return by reference.
course, you dont have to. The abs function takes To make a function return by reference put the &
arguments by reference. Do you remember what this will character in front of the function name. The reason why
do? If the abs function takes an argument by reference, the & character is put in front of the abs function is to
it can change the value of the variable use as an argument make the function return by reference and you will have
in the calling function as it wants. As a result, when the reference to what is returned by that function. By putting
variable value is changed in the abs function, the the & character in front of the abs function, we now have
variable x in the main function will be changed in the the reference to the absValue global variable and we
same manner. If you want this not happen, i.e. if you want can change its value as we want by calling the function.
the abs function not to change the value of x in the main That is what we did on line 19 of the program. We
function and if you just want to use the return value of assigned the return value of the abs function by a value
the abs function, you know what to do. Just avoid the & which wanted. In the program, an abs(x) value is
character from the signature of the abs function. compared with 3 on line 18 and assigned with 3 if it results
in a value greater than 3 on line 19. That is what the
By putting the & character from the signature of the abs
problem statement of the program said. After that, there
function, you have made the x variable of the main
is a cout statement on line 21 of the main function. It
function to have whatever the value variable of the
will display the value of x and absValue respectively
abs function gets. In the abs function, the value
along with other characters. Now, run the program and
variable is changed on line 11 only. What if you remove
enter -10 as an input. The message which you are be
this line from the program? The function still returns an
expecting on the display console might be this one:
absolute value of any value passed to it but the value of x
in the main function will not be changed. Confusing? Just
understand the following and it will no longer be
confusing. You are reasonable to expect this. Because when you pass
-10 as an argument and call the abs function for the first
The reference variable to the x variable in the abs
time on line 18, the value of x will be changed to the
function is the value variable which is defined on the
absolute value of -10, which is 10. You know why the
signature. Do you understand this? Good. If a variable has value of x is changed. It is because the function call is
a reference variable when will it change? It will be changed made by reference and the reference variable to x
when the original variable is changed or when the
(value) is changed inside the abs function. Therefore
reference variable is changed. Right? If neither of them
expecting the displayed value of x as 10 is reasonable and
were changed, then there will be no change in the original
By: Asaye Chemeda Email: asayechemeda@yahoo.com 9
right. But what about the displayed value of absValue? altogether. Can you guess what will happen if you define
Is the displayed value what you expected? It is again two functions with the same function name, with the
reasonable to expect its to have the same value as x. same number and data type of arguments and try to
because there is no statement where its value explicitly is compile it? The compiler will send an error message even
changed in the main function. However, when you run if their return type is different. For instance, look at the
the program, the message which you will get is this one. following program.
Program 1.12[Incorrect].cpp

You are correct about the displayed value of x. it is indeed


10. But the displayed value of absValue is 3. If you
understand the concept of returning by reference, you will
know why. Since there is & character in front of the abs
function name, you can change the return value of the
function by calling and assigning the function to any value
which you want. That is what line 19 of the program did.
It assigned a maximum value of 3 to the return value of
the abs function. This wouldnt have been possible, had
the abs function returned by value. To understand a little
bit more, let us answer the following string of questions.
What is the return value of the abs function? It is
absValue. Look at line 12 of the program. What type In the above program, there are two functions other than
of return method is used by the abs function? It is return the main function. The functions have the same function
by reference. Look at the & character on line 5 in front of name (print), the same number of arguments (one) and the
the function name. What happens when a function same data type of the arguments (double). Since the number
returns by reference? You can change the return value (i.e. of arguments is the same, the sequence of the data types of the
absValue) by calling and assigning a value to the argument list is also the same. Therefore, the functions
function. Where, in the program, did you call and assign have the same signature. If the functions vary by any of
a value to the abs function? On line 19. Which means these four highlighted factors, they no longer have the
that, on line 19, you set the maximum value to the same signature. But, one of the print functions takes a
absValue variable to 3 by using if statement. local variable named a while the other takes b as an
Therefore, if the absolute value of a number is greater argument. If so, why are their signatures the same? As we
than 3, the abaValue variable will have a value of 3. said earlier, the names which you give to the arguments
Since the absolute value of -10 is greater than 3, the are dummy variables and you can give it whatever name
displayed value of absValue is 3. By the way, you could you want without affecting the outcome. As a result, these
have also limited the value of absValue to 3 in the main dummy variables will not be used as a criteria to compare
function itself without calling the abs function. Because, whether two functions have the same signature or not.
the absValue variable is global and you can access it If a program contains, two or more functions with the
and change its value from anywhere in the program. The same signature, it will have compilation errors if you try
desired value of x which is stated in the problem to compile it. When a function call is made, you only write
statement is obtained from absValue variable not x. the signature of the called function. If a program has two
That is what returning by reference means. There you go. functions with the same signature, which function will the
Are you bored? You might be because we spent much compiler invoke when the function is called? The
time on the same topic. But, it was worth. Right? You program will get confused. The program is logical here. It
grabbed some interesting and basic concepts in C++. By is us who are trying to confuse the program. To stop
the way, if you understand about functions, it means that confusing the program, let us make only one change in
you have understood one of the core concepts of the Program 1.12. Let us change the data type of the
C++ language. To make it interesting again, let us switch argument of the second print function from double to
to another concept regarding functions. int. If you do so, by the criteria stated above, the two
print functions will no longer have the same signature.
This time, let us deal about function names, return types Right? Because, the data type of the only argument which
and argument lists in detail. When we say argument list, they take is different. This makes them to have different
we mean the argument variables and their data types
By: Asaye Chemeda Email: asayechemeda@yahoo.com 10
signatures. Have a look at line 8 of the changed program interesting results, why those results occurred will be
below. reasoned out in the next topic when another interesting
concept in C++ is discussed. When you deal about
Program 1.13[Correct].cpp object-oriented programming in C++, you often need
functions to have the same name but different signature.
This happens if the functions take different number or
data type or sequence of data type of the arguments. If
you define functions having the same name but different
signature in a program, then you are over-loading that
function. Since we are discussing about functions now, it
is worth dealing about this concept in detail here.
Function overloading
In C++, especially in object-oriented programming, the
name of functions may be restricted but you may want to
call those functions by passing distinct parameter lists. In
those situations, you have to define the functions with the
Note that the print functions take an arguments and same name but different signatures. Defining two or more
print its value. The value is printed as value of functions in a program with the same name but different
a in the first print function and value of signature is called function overloading. We have
b in the second. The print function is called on line already seen how function overloading is done in Program
13 of the program from the main function and the value 1.13. However, to understand some rules regarding which
of variable x is passed to the function as a parameter. The overloaded function is invoked by the compiler during a
variable x has double data type and is initialized with a function call, we will write another program. For this,
value of 100. If you run the program, there will be no eight overloaded functions will be defined. Is that too
compilation error now. Because the only cause for the many? You will see it will be worth the number. We will
compilation error in Program 1.12 is now gone. If you try to call the function by passing different parameters and
remember the cause, it was having two functions with the we will note which function is invoked. When a function
same signature within the program. As stated above, the gets invoked, it prints a message which has the functions
two print functions in program 1.13 are not identical rank number in the vertical order. So, we know which
any more. function was really invoked from the output message.
Here is the program.
When a function call is made on line 13, is the program
now confused to which print function will he go to? Program 1.14[Correct].cpp
Not anymore. It goes to the print function which has
the same argument data type as the data type of the
variable passed to it. You see how smart the program is!
The data type of x is double and when the print
function is called, the program directs the call to
whichever print function which takes a double value
as an argument. It is the first print function which takes
double value as an argument. Therefore, the value of x is
printed as value of a. Have a look at the
message below which results when the program is run.

See what happens when the data type of x is changed to


int. in addition try to call the function by passing different
data types directly. For instance, change line 13 of the
program with print(10.0);, print(10);and
print(x); and see what happens. Repeat these
changes after changing the data type of the argument of
the second print function to float. If you notice some

By: Asaye Chemeda Email: asayechemeda@yahoo.com 11


As you can notice in the above program, all the functions Now, we added a decimal point to the number 10 which
other than main have a function name of print. But all was passed in our previous attempt. If you run the
the functions have different signature i.e. some of them program again and have a look at the output, it is:
have distinct data type of arguments, some of them have
The fourth print function invoked.
different numbers of argument and the others have
distinct sequence of data type of arguments. But all of This output message will be displayed by the print
them have a unique signature. Thus, we can say that they function which take a double data type argument.
are overloaded functions. Reasonable. Right? If a number has a decimal point, it is
We will call the print function by passing different considered as a floating point number. And when a
floating point number is passed, the compiler will invoke
parameters from line 29 of the main function and run it
the overloaded function which takes an argument which
each time. If you run the program as it is, the output is:
matches this data type. You can raise an interesting
The first print function invoked. question here. In addition to the double data type, the
float data type is also used for floating point data types
This result is displayed because on line 29 of the program, like 10.0 and there is a print function which takes float
the print function is called with empty parameters. As data type as an argument. If so, why did the compiler
a result, the compiler invokes the print function which prefer the function with double data type argument list?
takes no parameters. In the vertical order, this particular Before answering this question, let us see how the C++
print function is the first one in the program. If you see data types are classified.
the body of the function, it has a cout statement which
prints the above message. Therefore, when an overloaded In C++, data types are classified into simple, structured
function is called with empty parameters, the compiler and pointers. Since their significance for this topic is
invokes the overloaded function which doesnt take any minimal, we will not discuss about the latter two here. The
parameters. simple data types are further classified into three
categories as integral, floating-point and enumeration.
Now let us change line 29 of the program with the The integral category can only deal with numbers and
statement below and run the program. i.e. let the function variables without decimal places. The int, char and bool
call passes a value of 10 (with no decimal point). data types fall in the integral data type category. In this
print(10); category, the int data type has higher level than the other
If you look at the output, it is: two. The floating-point category can deal with any
numbers with or without decimal places. The floating-
The second print function invoked. point category contains float and double data types.
If you find out which print function displays the above Among these two, double has higher level than float.
message when invoked, it is the print function which When we go back to our question and reason out why the
takes int parameter. Do you see the reason why the compiler preferred double over float, it is because double
complier invoked this particular print function? It is is at higher level than float.
because the compiler considers a value of 10 without a
decimal point as an integer and it invokes the overloaded Rule 2: if function call is made to an overloaded function and the
print function which takes a similar data type argument compiler has the option to choose between different data types in the
as the passed argument data type. same category, without data type conversion, the compiler will invoke
the function which takes arguments with a higher level data type
Rule 1: when a function call is made to an overloaded function, the among the list of options.
compiler will first try to find and invoke the function which takes the Therefore, if two overloaded functions exist one of them
same data type and the same sequence of data types of arguments as taking argument with float data type and the other taking
those of the arguments passed from the calling function.
with double data type, and if a floating-point number
Which means, if an int data type is passed as an argument (not variable) is passed as an argument, the compiler
from the calling function, it is the overloaded function invokes the function which takes an argument with
which takes argument with int data, if there is, which will double data type. However, if a variable is passed, the
be invoked. compiler will invoke the function which takes the same
Let us make what we are doing more interesting by data type as the variable, whether it is double or float. To
replacing line 29 of the program with the following. understand this more, define a variable with double or
float data type, initialize it and pass it as an argument and
print(10.0); see which function will be invoked.
By: Asaye Chemeda Email: asayechemeda@yahoo.com 12
Now, have a look at all the print functions and their print(10.0,C++);
argument lists. Is there any one of them which takes an It is the fifth print function, right? Because, this
argument with char data type? None, right? But let us
pass a parameter of char data type and make a function particular print function has the same sequence of data
call and see what happens. Just change line 29 with the type of arguments as the passed arguments. Therefore, its
following and run the program. invocation is not a surprise. This concludes our discussion
on function overloading.
print(c);
The following message will be displayed. Before proceeding to the last topic of this chapter, let us
see some real world C++ functions. Suppose you are a
The second print function invoked. programmer in a bank and you are given a task of writing
a piece of code by your boss. The piece of code which you
If you note which print function was invoked, it is the have to write is a function which calculates the current
one which takes an int data type argument. The passed amount of money for the banks customers. Obviously,
argument is of char data type and the invoked function the current amount is dependent on the principal amount
takes int data type. Why so? of money (the value at the previous current amount), the
When a char data type is passed, the compiler will look period between the previous and this current amount
for the overloaded function which takes a char data type calculation and the interest rate. In short, the current
argument (Rule 1). If the compiler couldnt find any, the amount is dependent three variables: principal amount,
compile will invoke the function which takes int data type period and interest rate.
(since int is at higher level in this group, see Rule 2). Based on what we discussed so far, you will tend to define
Rule 3: if function call is made to an overloaded function and Rule a function which takes three parameters. Or do you have
1, which is stated above, failed, the compiler will look for and invoke another approach? Unless one or more of the three
the function which takes a data type which is at higher level in the variables is defined as a global variable or unless you
same category as the data type of the passed argument. obtain their values by calling another function or other
Read Rule 2 in detail first and a basic point regarding Rule object-oriented programming approach, the function
2 should be discussed at this point in accordance with which you are going to write should take the values of
these variables as parameters.
Rule 3. If there is a data conversion, for instance, from int
to double or float, Rule 2 is not valid anymore and the Let us say your function takes these three variables as
compiler will result in an error. parameters. As employee of the bank, say, you know that
While trying to invoke an overloaded function, if all the the interest rate of the bank changes only in rare
above three rules fail and the compiler finds it ambiguous conditions. Therefore, it may be unwise to create a
to choose between two functions, the compiler will send function which always takes the value of this variable as
an error message. For instance, try to replace line 29 of an argument. At the same time, if you remove it from the
the program with the following and run it. argument list, your function will not work in those rare
conditions where the interest rate might change. So, what
print(10.0,10.0); would you do?
When you run the program, the compiler will get There is another approach which you can do. It wasnt
difficulty in choosing between the seventh and eighth discussed in this chapter but it will solve your problem.
print functions. Because with the above three rules, Here is the solution. You will still make your function to
you cannot justify which one the compiler should have take three variables but you will initialize the interest rate
invoked. But try to make the data types of both the variable on the signature of your function with the rarely
arguments of the last print function double and run changed interest rate value. You have to also make this
the program. Now, you will see that this changed print variable, the right-most variable in the argument list. What
function will be invoked because of Rule 2. will happen if you do so? Your function can be invoked
by passing only the other two variables. If your function
Do you think that sequence of data types also matters in
is called with only two parameters, by default, it takes the
selecting which function to invoke? Of course it does. If
you see the fifth and sixth print functions closely, both initialized value the interest rate from the signature and
take a double and string data type but with a different calculates the current amount. If the bank changes its
sequence. Which print function will be invoked if you interest rate, your function can be called with three
change line 29 with the following statement and run the parameters, the third parameter being the new interest
program? rate value. When your function is called with three

By: Asaye Chemeda Email: asayechemeda@yahoo.com 13


parameter, it will not use the initialized interest rate value. value of 1. On the right hand side of the signature, there
It will use the new one. Problem solved! are three dots after a coma. Therefore, we expect the
function to take any number and data type of arguments.
By the way, do you know what such kind of parameters, When this function is invoked, it will display two
like that of the interest rate, are called? They are called messages which you can see from the body of the
default parameters in C++. If you initialize parameters, in function. One of them is printing the value of the default
the signature of the function, those parameters are called parameter.
default parameters. Default parameters should always
be written on the right hand side of the argument list. The print function is called from the main function
When you call the function, you can omit passing the three times by passing different number and data type of
values of default parameters. In a function having more arguments. All of these invoked the print function. The
than one default variable, if you omit a default variable, all first call with empty parameter invoked the print
the default parameters on the right hand side of the function only because the only mandatory argument in
omitted default parameter should also be omitted. During the print function is a default parameter. If you remove
function call, if the default parameter is omitted, the the initialization from the signature of the print
function uses the default values in the signature. If you function, there will be compilation error. Because when
pass the values of the default parameters during a function you call functions with variable-length argument lists, you
call, the passed values will override the default values. have to at least pass one argument unless that argument
is a default parameter.
Interesting! Isnt it? The default parameters concept made
your function to be dynamic. Let us see if there are ways The displayed message when you run the program is
by which a function can be made more dynamic in C++. shown below.
Now consider another scenario than your bank
assignment. What if you want to make a single function
take unlimited numbers of arguments with unlimited data
type? Is there a possibility? Of course, there is. Didnt we
say, C++ is versatile? You can also define a function
which takes unlimited number of arguments in C++. To
define such a function, two conditions are mandatory
though. The first one is, the function should have at least From the output message we can notice that the print
one defined argument. The second one is you have to put function is invoked three times. During the first
three dots after a coma on the right hand side of the invocation, the value of a was not passed and the default
signature of the function. That is it. If you define a value is printed. During the second and the third
function fulfilling these two conditions, the function can invocations, the passed values of a were printed
now take any number and data type of arguments. In this overriding the default value.
case the function is said to take variable-length We have almost covered what we have to discuss in this
argument lists. chapter. Only one topic is remaining. The concept which
To understand the concept of default parameters and we are going to discuss in this last topic will help us
variable-length argument lists, have a look at the following understand a way by which we can reduce the
program. computation time while working with frequently called
functions. When normal functions are called there are
Program 1.15[Correct].cpp
overhear (regular) function call procedures. These
procedures might take a considerable computation time
and under certain programming circumstances, every
nanosecond might be precious. At the compilers will,
however, there is a way by which we can avoid these
overhead function call procedures, by using special types
of functions. These special functions will be the last topic
of this chapter.
Inline functions
In an environment where computation time is very
In the above program, the print function has one precious, avoiding the overhead function call procedures
default parameter (a) which is initialized with a default might be very useful. C++ has the facility to avoid these
By: Asaye Chemeda Email: asayechemeda@yahoo.com 14
procedures, at the compilers will, by using special Our discussion about one of the fundamental concepts in
functions called inline functions. When inline functions C++, function, is now over? It was interesting, right?
are called in a program, the compiler will replace the call Hopefully, you have grasped the basic knowledge about
by the corresponding code of the functions. In other functions. There is a lot more to grab and let us go for it.
words, the body of the inline functions acts as if it is
expanded at the place where the function is call is made.
Because of this, those overhead function call procedures
will be avoided.
To make functions inline, putting the inline keyword in
front of the function definition is sufficient. Putting the
keyword will request the compiler to expand the function
inline while it is invoked. The compiler will not take this
as a command and the functions will be expanded only if
the compiler accepts the request. If the compiler finds the
function to be too complicated, it may reject the request
and consider it as a normal function even if there is an
inline key word in front of the function definition. It is
advisable not to have prototype of inline functions.
Because if an inline function has a prototype, the compiler
will consider it just as a normal function.
There may also be a drawback associated with inline
functions. As one of the benefits of having functions is to
save memory, when the compiler expands the inline
function at the place of the function call, this benefit may
be lost.
The following program shows an example of an inline
function.
Program 1.16[Correct].cpp

In the above program, the maximum function is an inline


function. If the compiler expands the function during the
function call. The above program is equivalent to the
program shown below.
Program 1.17[Correct].cpp

By: Asaye Chemeda Email: asayechemeda@yahoo.com 15

Vous aimerez peut-être aussi