Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

FUNCTIONS IN C++

By MRI 9/22/2017 1
Functions in C++
Functions are used to provide modularity to a
program. Creating an application using function
makes it easier to understand, edit, check errors
etc.
Functions allow to structure programs in segments
of code to perform individual tasks.

In C++, a function is a group of statements that is


given a name, and which can be called from some
point of the program.

By MRI 9/22/2017 2
Functions in C++
Depending on whether a function is predefined or
created by programmer; there are two types of
function:

1. Library Function
2. User-defined Function

By MRI 9/22/2017 3
User Defined Functions in C++
Syntax of Function
return-type function-name (parameters)
{
// function-body
}
return-type : suggests what the function will return. It can be int,
char, some pointer or even a class object. There can be functions
which does not return anything, they are mentioned with void.
Function Name : is the name of the function, using the function
name it is called.
Parameters : are variables to hold values of arguments passed
while function is called. A function may or may not contain
parameter list.
By MRI 9/22/2017 4
Function prototype (declaration)
If a user-defined function is defined after main()
function, compiler will show error.
It is because compiler is unaware of user-defined
function, types of argument passed to function and
return type.
In C++, function prototype is a declaration of
function without its body to give compiler
information about user-defined function.

By MRI 9/22/2017 5
Declaring, Defining and Calling Function

#include < iostream>


using namespace std;
int sum (int x, int y); //declaring function
int main()
{
int a = 10;
int b = 20;
int c = sum (a, b); //calling function
cout << c;
}
int sum (int x, int y) //defining function
{
return (X + y);
}
By MRI 9/22/2017 6
Declaring, Defining and Calling Function

Here, initially the function is declared, without body.


Then inside main() function it is called, as the function
returns summation of two values, hence c is their to
store the value of sum.
Then, at last, function is defined, where the body of
function is mentioned. We can also, declare & define the
function together, but then it should be done before it is
called.

By MRI 9/22/2017 7
Calling a Function
Functions are called by their names. If the function is
without argument, it can be called directly using its
name. But for functions with arguments, we have two
ways to call them:
1. Call by Value
2. Call by Reference

By MRI 9/22/2017 8
Call by Value
In this calling technique we pass the values of
arguments which are stored or copied into the formal
parameters of functions. Hence, the original values are
unchanged only the parameters inside function changes.
void calc(int x);
int main()
{
int x = 10;
calc(x);
printf("%d", x);
}
void calc(int x)
{
x = x + 10 ;
}
By MRI 9/22/2017 9
Output : 10
Call by Value
In this case the actual variable x is not changed,
because we pass argument by value, hence a
copy of x is passed, which is changed, and that
copied value is destroyed as the function
ends(goes out of scope).
So the variable x inside main() still has a value 10.

By MRI 9/22/2017 10
Call by Value
But we can change this program to modify the
original x, by making the function calc() return a
value, and storing that value in x.
void calc(int x);
int main()
{
int x = 10;
calc(x);
printf("%d", x);
}
void calc(int x)
{
x = x + 10 ;
return x;
}
Output : 20 By MRI 9/22/2017 11
Call by Reference
In this we pass the address of the variable as arguments. In this
case the formal parameter can be taken as a reference or a pointer,
in both the case they will change the values of the original
variable.
void calc(int *p);
int main()
{
int x = 10;
calc(&x); // passing address of x as argument
printf("%d", x);
}
void calc(int *p)
{
*p = *p + 10;
}
Output : 20
By MRI 9/22/2017 12
Types of User-defined Functions in C++

By MRI 9/22/2017 13
Example 1: No arguments passed and no return value
# include <iostream>
using namespace std;
void prime();
int main()
{
prime(); // No argument is passed to prime()
return 0;
}
// Return type of function is void because value is not returned.
void prime()
{
int num, i, flag = 0;
cout << "Enter a positive integer enter to check: ";
cin >> num;
for(i = 2; i <= num/2; ++i)
{
if(num % i == 0)
{
flag = 1;
break;
}
}
if (flag == 1)
{
cout << num << " is not a prime number.";
}
else { cout << num << " is a prime number."; .
} By MRI 9/22/2017 14
Inline function
Calling a function generally causes a certain
overhead (stacking arguments, jumps, etc...),
and thus for very short functions, it may be more
efficient to simply insert the code of the function
where it is called, instead of performing the
process of formally calling a function.

By MRI 9/22/2017 15
Inline function
Preceding a function declaration with the inline
specifier informs the compiler that inline
expansion is preferred over the usual function
call mechanism for a specific function.
This does not change at all the behavior of a
function, but is merely used to suggest the
compiler that the code generated by the function
body shall be inserted at each point the function
is called, instead of being invoked with a regular
function call.

By MRI 9/22/2017 16
Inline function
C++ inline function is powerful concept that is
commonly used with classes. If a function is
inline, the compiler places a copy of the code of
that function at each point where the function is
called at compile time.
To inline a function, place the
keyword inline before the function name and
define the function before any calls are made to
the function.
The compiler can ignore the inline qualifier in case
defined function is more than a line.

By MRI 9/22/2017 17
Inline function
Following is an example, which makes use of
inline function to return max of two numbers:

#include <iostream>
using namespace std;
inline int Max(int x, int y)
{ return (x > y)? x : y; }
// Main function for the program
int main( ) {
cout << "Max (20,10): " << Max(20,10) << endl; cout <<
"Max (0,200): " << Max(0,200) << endl; cout << "Max
(100,1010): " << Max(100,1010) << endl; return 0;
}

By MRI 9/22/2017 18
Friend function
A friend function of a class is defined outside that
class' scope but it has the right to access all
private and protected members of the class.
Even though the prototypes for friend functions
appear in the class definition, friends are not
member functions.
A friend can be a function, function template, or
member function, or a class or class template, in
which case the entire class and all of its
members are friends.

By MRI 9/22/2017 19
Friend function
To declare a function as a friend of a class,
precede the function prototype in the class
definition with keyword friend as follows:

class Box {
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};

By MRI 9/22/2017 20
Friend function
#include <iostream>
using namespace std;
// forward declaration
class B;
class A
{
private:
int numA;
public:
A(): numA(12) { } // friend function declaration
friend int add(A, B);
};
class B {
private:
int numB;
public:
B(): numB(1) { } // friend function declaration
friend int add(A , B);
};
// Function add() is the friend function of classes A and B
// that accesses the member variables numA and numB
int add(A objectA, B objectB)
{
return (objectA.numA + objectB.numB);
}
int main()
{ A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
By MRI 9/22/2017 21
Friend function
In this program, classes A and B have declared
add() as a friend function.
Thus, this function can access private data of both
class.
Here, add() function adds the private data numA
and numB of two objects objectA and objectB, and
returns it to the main function.
To make this program work properly, a forward
declaration of a class class B should be made as
shown in the above example.
This is because class B is referenced within the
class A using code: friend int add(A , B);.

By MRI 9/22/2017 22
Recursive function
A function that calls itself is known as recursive
function. And, this technique is known as
recursion.
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
} By MRI 9/22/2017 23
By MRI 9/22/2017 24
Examples of Recursive Function
// Factorial of n = 1*2*3*...*n
#include <iostream>
using namespace std;
int factorial(int);
int main()
{
int n;
cout<<"Enter a number to find factorial: ";
cin >> n;
cout << "Factorial of " << n <<" = " << factorial(n);
return 0;
}
int factorial(int n)
{
if (n > 1)
{
return n*factorial(n-1);
}
else
{
return 1;
}
}
By MRI 9/22/2017 25

You might also like