0% found this document useful (0 votes)
4 views28 pages

Chapter 5 functions

Chapter 5 discusses the concept of functions in C++, emphasizing their importance in avoiding code repetition and enhancing program modularity. It covers function declaration, definition, calling, return types, and the use of prototypes, along with examples demonstrating these concepts. The chapter also introduces advanced topics such as default arguments, function overloading, and the distinction between return type and void functions.

Uploaded by

bezabih bekele
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)
4 views28 pages

Chapter 5 functions

Chapter 5 discusses the concept of functions in C++, emphasizing their importance in avoiding code repetition and enhancing program modularity. It covers function declaration, definition, calling, return types, and the use of prototypes, along with examples demonstrating these concepts. The chapter also introduces advanced topics such as default arguments, function overloading, and the distinction between return type and void functions.

Uploaded by

bezabih bekele
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/ 28

CHAPTER 5

FUNCTION c++
Argument

 A block or Subroutine
 Function
 Function declaration
 Function definition
 Function call
 Function return type Return
Why functions in programming
• A block defined as list of statements in pair of curly braces { }
• Frequently, the same piece of code may be required written over again in many different parts of
a program code.
• Instead of repeating the code every time it is needed, there is an obvious advantage if the
common instructions are written only once. How to make them in use once written?
• These blocks are to produce result(which is called return data)
• And need to identify them by name, in naming return type is mentioned. Thus functions of the
same name may be identified by there return type.
• A set of common instructions that can be used in a program many times are called a subroutine.
Then when named we call them functions.
• When we want to use the subroutine we call the function in a statement by its name then the
execution goes to the function location. After return go back to the next statement in main.
• After the function has been executed, a branch (return) is made back to the main program.
• Statements used are
for calling/branching to the subroutine
for return to the main
Use function
Get Started with an Example Suppose that we need to evaluate the area of a
circle many times, it is better to write a function called getArea(), and re-use it
when needed.
Caller-main()
Functon–getArea()

ete r(s)
m
Para

Retu
rn / re
sult
cont

.
At times, a certain portion of codes has to be used many times. Instead of re-writing the codes
many times, it is better to put them into a "subroutine/function", and "call" this “functions"
many time for ease of maintenance, understanding and efficient use of memory. Subroutine is
called method (in Java) or function (in C/C++).
The benefits of using functions are:
• Divide and conquer: construct the program from simple, small pieces or components.
• Modularize the program into self-contained tasks.
• Avoid repeating codes: It is easy to copy and paste, but hard to maintain and synchronize all the
copies.
• Software Reuse: you can reuse the functions in other programs, by packaging them into library
codes.

Two parties are involved in using a function:


• A Caller, who calls the function, and the function called. The caller passes argument(s) to the
function. The function receives these argument(s), performs the programmed operations
within the function's body, and returns a piece of result back to the caller.
Cont.
• A function is a group of statements together perform a specific task.
• Every C++ program has at least one function which is main(), all the most trivial programs can
define additional function.
• C++ code starts from main() function
• To ease programming and save time and energy compiler IDE provides primitive type built in
function in different named libraries those can be included in the header like maths in Borland
turbo C++.
• These functions are called library function(built in functions) identify them by name and purpose.
And use them by calling.
• The other functions are externally constructed by programmer. Called user defined functions.
• The other classification is according to their process how they react to.
• Thus functions used to produce processed data are called return type functions. The others which
works to display rather to return them(pass them to others). Are called void type functions.
Cont
#include <iostream.h>
#define PI 3.14159265
double getArea(double radius); // Function Prototype (Function Declaration
int main() {
double radius1 = 1.1, area1, area2;
area1 = getArea(radius1); // call function getArea()
cout << "area 1 is " << area1 << endl;
area2 = getArea(2.2); // call function getArea()
cout << "area 2 is " << area2 << endl;
cout << "area 3 is " << getArea(3.3) << endl; // call function getArea()
}

double getArea(double radius) // Function Definition


{
return radius * radius * PI; // Return the area of a circle given its radius

}
In the above example, a reusable function called getArea() is defined, which
receives a parameter (in double) from the caller, performs the calculation, and
return a piece of result (in double) to the caller. In the main(), we invoke
getArea() functions thrice, each time with a different parameter.

In C++, you need to declare a function prototype (before the function is used),
and provide a function definition, with a body containing the programmed
Function definition
operations.

The syntax for function definition is as follows:


returnValueType functionName(parameterList){
functionBody ;
}
The parameterList consists of comma-separated parameter-type and parameter-name, i.e., param-1-
type param-1-name, param-2-type param-2-name,...
The returnValueType specifies the type of the return value, such as int or double. An special return
type called void can be used to denote that the function returns no value. In C++, a function is allowed
to return one value or no value (void). It cannot return multiple values. [C++ does not allow you to
return an array!]
• The “return”
statement
A function's name shall be a verb or verb phrase (action), comprising one or
more words. The first word is in lowercase, while the rest are initial-capitalized
(known as camel-case).

For example, getArea(), setRadius(), moveDown(), isPrime(), etc.

Function Prototype:
In C++, a function must be declared before it can be called. It can be achieved
• Function
by either Naming
placing Convention
the function andbefore
definition function
it is being used, or declare a so-
prototype
called function prototype.
Inside the function's body, you could use a return statement to return a value
(of the return Value Type declared in the function's header) and pass the control
back to the caller. The syntax is:
return expression; /* Evaluated to a value of return
Value Type declared in function's signature */
return; // For function with return type of void
Take note that invoking a function (by the caller) transfers the control to the
function. The return statement in the function transfers the control back to the
caller.
Con
t.
You could optionally include the parameter names in the function prototype. The
names will be ignored by the compiler, but serve as documentation. For example,

// Function Prototype
double getArea(double radius);
/*parameter names are ignored, but serve as documentation */
int max(int x, int y);

Function prototypes are usually grouped together and placed in a so-called header
file. The header file can be included in many programs. We will discuss header file
later.
Cont.
Another Example:
We have a function called max(int, int), which takes two int and return their
maximum. We invoke the maxm() function from the main().
#include<iostream.h>
int maxm(int,int); // Function prototype (declaration)
int main(){
cout<<maxm(5,8)<<endl; // Call maximum() with literals
int a=6,b=9,c;
c=maxm(a,b); // Call maximum() with variables
cout<<c<<endl;
cout<<maxm(c,99)<<endl; // Call maximum()
}
// Function definition
// A function that returns the maximum of two given int
int maxm(int x,int y) {
return(x>y)?x:y;
}
Boolean
Functions
A Boolean function returns a bool value (of either true or false) to the caller.
Suppose that we wish to write a function called isOdd() to check if a given number is odd.

start
#include<iostream.h>
bool isOdd(int); // Function Prototype
int main(){ Get n; N=0
bool alpha;
cout<<bool alpha; // print bool as
true or false N x =(n – 1)
cout<<isOdd(5)<<endl; // true
cout<<isOdd(6)<<endl; // false
cout<<isOdd(-5)<<endl; // false n≤0
}
bool isOdd(int number) { Output N
if(number%2==1) {
return true;
} else{
return false; end
}
}
The above code produces the correct answer, but is poor. For boolean function,
you should simply return the resultant bool value of the comparison, instead of
using a conditional statement, as follow:

This seemingly correct codes bool isEven(int number){


produces false for -5, return (number%2==0);
because -5 % 2 is -1 instead }
of 1. You may rewrite the bool isOdd(int number){
condition: return !(number %2==0); // OR
return !isEven(number);
bool isOdd(int number) { }
if (number % 2 == 0) { int main(){
return false;
} else {
int number=-9;
return true; if(isEven(number)){ // Don't
} write(isEven(number)==true)
} cout<<"Even"<<endl;
}
}
The "void" Return Type
• Suppose that you need a function to perform certain actions (e.g., printing) without a need
to return a value to the caller, you can declare its return-value type as void.
• In the function's body, you could use a "return;" statement without a return value to return
control to the caller. In this case, the return statement is optional.
• If there is no return statement, the entire body will be executed, and control returns to the
caller at the end of the body.

Default
Arguments
C++ introduces so-called default arguments for functions. These default values would be
used if the caller omits the corresponding actual argument in calling the function. Default
arguments are specified in the function prototype, and cannot be repeated in the function
definition. The default arguments are resolved based on their positions. Hence, they can
only be used to substitute the trailing arguments to avoid ambiguity. For example see on
next page,
Cont. #include <iostream.h>
//Function prototype-Specify the default arguments here
you should specify int add1(int=1,int=2,int=3);
the default int add2(int,int,int=3);
arguments in the int main(){
function prototype cout<<add1(4,5,6)<<endl;// No default
(declaration). They cout<<add1(4,5)<<endl;//4,5,3(default)
can only be defined cout<<add1(4)<<endl;//4,2(default), 3(default)
once (one-definition cout<<add1()<<endl; // 1(default), 2(default),3(default)
rule), and cannot be cout<<add2(4,5,6)<<endl;// No default
repeated in the cout<<add2(4,5)<<endl;//4,5,3(default)
function definition. /* cout<<add2(4)<<endl;
error: too few arguments to function 'int
Default argument is fun2(int,int,int)’*/
not absolutely }
necessary. The codes int add1(int n1,int n2,int n3) {
could be hard to //cannot repeat default arguments in function definition
maintain. return n1+n2+n3;
}
int add2(int n1, int n2, int n3) {
return n1 + n2 + n3;
}
Exampl
Function Overloading e:
#include <iostream.h>
C++ introduces function overloading (or void fun(int, int, int); // Version 1
function polymorphism, which means void fun(double, int); // Version 2
many forms), which allows you to have void fun(int, double); // Version 3
multiple versions of the same function int main() {
fun(1,2,3); // version 1
name, differentiated by the parameter list
fun(1.0,2); // version 2
(number, type or order of parameters). The fun(1,2.0); // version 3
version matches the caller's argument list fun(1.1,2,3);}
will be selected for execution. For example void fun(int n1, int n2, int n3){ // version 1
see next page, Overloaded functions cout<<"version 1"<< endl;
}
cannot be differentiated by the return-type
void fun(double n1, int n2){ // version 2
(compilation error). cout<<"version 2"<< endl;
}
void fun(int n1,double n2){ // version 3
cout<<"version 3"<< endl;
}
/* version 1 - double 1.1 casted to int 1 (without warning), fun(1, 2, 3, 4); error:
no matching function for call to 'fun(int, int, int, int)‘ fun(1, 2); error: call of
overloaded 'fun(int, int)' is ambiguous note: candidates are: void fun(double, int)
void fun(int, double) fun(1.0, 2.0); error: call of overloaded 'fun(double, double)'
is ambiguous*/
Function format:
(Type, Name, Argument, Statement)
 Using functions we can structure our programs in a more modular way, accessing all the potential that structured
programming in C++ can offer us.
 A function is a block of instructions that is executed when it is called from some other point of the program. The
following is its format:

type name ( argument1, argument2, ...) statement


where:
• type is the type of data returned by the function.
• name is the name by which it will be possible to call the function.
• arguments (as many as wanted can be specified). Each argument consists of a type of data followed by its identifier,
like in a variable declaration (for example, int x) and which acts within the function like any other variable. They
allow passing parameters to the function when it is called. The different parameters are separated by commas.
• statement is the function's body. It can be a single instruction or a block of instructions. In the latter case it must be
delimited by curly brackets {}.
Cont.  In order to examine this code, first of all remember
 Here you have the first function something said at the beginning of this course: a
example: C++ program always begins its execution with the
// function example main function. So we will begin there.
#include<iostream.h>  We can see how the main function begins by
int addition (int a, int b){ declaring the variable z of type int.
int r;  Right after that we see a call to addition function.
r=a+b; If we pay attention we will be able to see the
return(r); similarity between the structure of the call to the
} function and the declaration of the function itself
int main(){ in the code lines above:
int z; • The parameters have a clear correspondence.
z = addition (5,3); Within the main function we called to addition
cout<<"The result is "<<z; passing two values: 5 and 3 that correspond to
return 0; the int a and int b parameters declared for the
} function addition.
• At the moment at which the function is called from main,
control is lost by main and passed to function addition. The
The result is 8 value of both parameters passed in the call (5 and 3) are
copied to the local variables int a and int b within the
function.
Cont
.
• Function addition declares a new variable (int r;), and by means of the expression r=a+b;, it assigns to r the
result of a plus b. Because the passed parameters for a and b are 5 and 3 respectively, the result is 8.
• The following line of code:
return (r);
• Finalizes function addition, and returns the control back to the function that called it (main) following the
program from the same point at which it was interrupted by the call to addition.

But additionally, return was called with the content of variable r (return (r);), which at that moment was 8, so
this value is said to be returned by the function.

The value returned by a function is the value given to the function when it is evaluated. Therefore, z will store
the value returned by addition (5, 3), that is 8. To explain it another way, you can imagine that the call to a
function (addition (5,3)) is literally replaced by the value it returns (8).
The following line of code in main is:
cout << "The result is " << z;
that, as you may already suppose, produces the printing of the result on the screen.
Cont
.Scope of variables [re]
 The scope of variables declared within a function or any other block of instructions is only their
own function or their own block of instructions and cannot be used outside of them.
 For example, in the previous example it had been impossible to use the variables a, b or r
directly in function main since they were local variables to function addition. Also, it had been
impossible to use the variable z directly within function addition, since this was a local variable
to the function main.
 The scope of local variables is limited to the same nesting level in which they are declared.
Nevertheless you can also declare global variables that are visible from any point of the code,
inside and outside any function.
• use the variables a, b or r directly in function main since they were local variables to function addition. Also, it had
been impossible to use the variable z directly within function addition, since this was a local variable to the function
main.
• Therefore, the scope of local variables is limited to the same nesting level in which they are declared. Nevertheless
you can also declare global variables that are visible from any point of the code, inside and outside any function. In
order to declare global variables you must do it outside any function or block of instructions, that means, directly in
the body of the program.
• In order to declare global variables you must do it outside any function or block of instructions, that means, directly
in the body of the program.
Exampl
e: In order to understand well these examples you must
#include<iostream.h> consider once again that a call to a function could be
int subtraction(int a,int b){ perfectly replaced by its return value. For example the
int r; first case (that you should already know because it is the
r=a-b; same pattern that we have used in previous examples):
return(r); z = subtraction (7,2);
} cout << "The first result is " << z;
int main(){ If we replace the function call by its result (that is 5), we
int x=5,y=3,z; would have:
z=subtraction(7,2); z = 5;
cout << "The first result is " << z;
cout<<"The first result is
As well as
"<<z<<'\n'; cout << "The second result is " << subtraction (7,2);
cout<<"The second result is has the same result as the previous call, but in this case
"<<subtraction(7,2)<<'\n'; we made the call to subtraction directly as a parameter
cout<<"The third result is for cout. Simply imagine that we had written:
"<<subtraction(x,y)<<'\n'; cout << "The second result is " << 5;
z=4+subtraction (x,y); since 5 is the result of subtraction (7,2).
cout<<"The fourth result is"<<z
<<'\n'; Output on screen
The first result is 5
return 0; The second result is 5
} The third result is 2
The fourth result is 6
Cont
.In the case of cout << "The third result is " << subtraction (x,y);
The only new thing that we introduced is that the parameters of subtraction are variables instead of constants. That is
perfectly valid. In this case the values passed to the function subtraction are the values of x and y, that are 5 and 3
respectively, giving 2 as result.
The fourth case is more of the same. Simply note that instead of: z = 4 + subtraction (x, y);
we could have put: z = subtraction (x, y) + 4;
with exactly the same result. Notice that the semicolon sign (;) goes at the end of the whole expression. It does not
necessarily have to go right after the function call. The explanation might be once again that you imagine that a function
can be replaced by its result: z = 4 + 2;
z = 2 + 4;
Functions with no types -The use
of void
• If you remember the syntax of a function declaration:
type name ( argument1, argument2 ...)
statements

you will see that it is obligatory that this declaration begins with a type, that is the type of the data that will be returned
by the function with the return instruction. But what if we want to return no value?
• Imagine that we want to make a function just to show a message on the screen. We do not need it to return any
value, moreover, we do not need it to receive any parameters. For these cases, the void type was devised in the C++
language. Take a look at:
Exampl Output screen
// void function example
e: #include<iostream.h>
void dummyfunction(void){
I'm a function!
cout<<"I'm a
function!";
}
int main(){ • Although in C++ it is not necessary to specify
dummyfunction (); void, its use is considered suitable to signify
that it is a function without parameters or
return 0;
arguments and not something else.
}
• What you must always be aware of is that the format for calling a function includes specifying its name and
enclosing the arguments between parenthesis. The non-existence of arguments does not exempt us from the
obligation to use parenthesis. For that reason the call to dummyfunction is
dummyfunction ();
• This clearly indicates that it is a call to a function and not the name of a variable or anything else.
Arguments passed by value and by reference

• Until now, in all the functions we have seen, the parameters passed to the functions have been passed by value.
This means that when calling a function with parameters, what we have passed to the function were values but
never the specified variables themselves. For example, suppose that we called our first function addition using
the following code :
int x=5, y=3, z;
z = addition ( x , y );
• What we did in this case was to call function addition passing the values of x and y, that means 5 and 3
respectively, not the variables themselves.
Return value can be directed as a parameter

A parameter can be directly a function returns. This avoids variable declaration many times.

It can be written
equivalently:
Cont
. // passing parameters by reference
• This way, when function addition is being called the #include<iostream.h>
value of its variables a and b become 5 and 3 void Abiy(int& a,int& b,int& c){
respectively, but any modification of a or b within the a*=2;b*=2;c*=2;
function addition will not affect the values of x and y }
outside it, because variables x and y were not passed int main(){
themselves to the function, only their values. int x=1,y=3,z=7;
Abiy(x,y,z);
• But there might be some cases where you need to cout<<"x="<<x<<",y="<<y<<",z="<<z;
manipulate from inside a function the value of an return 0;
external variable. For that purpose we have to use }
arguments passed by reference, as in the function
‘Abiy’ of the following example:
output x=2, y=6, z=14

• See what may come if we remove & operator in the function definition.
• Can we create an other version of the same function in this fashion? will it work
fine? Try it
Cont.
• The first thing that should call your attention is that in the declaration of trump the type of each argument was
followed by an ampersand sign (&), that serves to specify that the variable has to be passed by reference instead of
by value, as usual.
 When passing a variable by reference we are passing the variable itself and any modification that we do to that
parameter within the function will have effect in the passed variable outside it.

Void Abiy (int&a,int&b,int&c)

Abiy(x,y,z)
• If when declaring the following function:
Void Abiy(int& a, int& b, int& c)
we had declared it thus:
void Abiy(int a, int b, int c)
that is, without the ampersand (&) signs, we would have not passed the variables by reference, but their values, and
therefore, the output on screen for our program would have been the values of x, y and z without having been
modified.
• Passing by reference is an effective way to allow a function to return more than one single value. For example, here
is a function that returns the previous and next numbers of the first parameter passed.
Cont.
// more than one returning value
#include<iostream.h> Previous=99, Next=101
void prevnext(int x,int& prev,int& next){
prev=x-1;
next=x+1;
}
int main({
int x=100,y,z;
prevnext(x,y,z);
cout<<"Previous="<<y<<",Next="<<z;
return 0;
}
THANK
S

You might also like