Vous êtes sur la page 1sur 31

Functions

Unit :4
Syllabus:
1. Introduction to functions.
2. Classification of c++ functions.
1. Built in functions.
2. user defined functions:-
a. Function declaration or function
prototype.
b. Function definition.
c. Function call.
3. Category of function prototype.
4.Argument of a function:-
a. call by value.
b. call by reference.
5. Function overloading.
6. Inline function.
7.recursion.
8. String handling function.
9.Dynamic memory allocation.
10. Math functions.
Introduction to functions.

A function is a self contained block of code that
performs a particular task. Once a function has
been design, it can be treated as black box that
takes some data from the main program and
return a value.
The inner details of a operation is invisible to the
rest of the program, all that a program knows
about the function is:-
What input goes in.
What output comes out.
Every program can be design using a collection
of these black box, known as function.
Classification of c++ functions
The c++ function can be classified into 2 categories:
1. Built in functions or library functions.
2. user defined functions.
Main() is an example of user defined function.
The distinction between these two categories is that, the
library functions are not written by us whereas a user
defined function has to be developed by the user at the
time of writing a program.however a user defined
function later become a part of c++ program library.



Advantages of functions
There are times when certain type of operations or
calculations is repeated at many points throughout a
program. In such situations, we may repeat the program
statements wherever the are needed which leads to a
number of problems such as too large and complex
code,unnessasary repetition of task etc.
The solution for the above problem is to design a function
that can be called and used whenever requried,which has
advantages such as:
1. It saves both time and space.
2. The length of the source program can be reduced by using
function.
3. A function can be used by many other programs.
4. It is easy to locate and isolate a faulty function for further
investigations.



Built in functions or library functions.
The c++ provide series of functions already made so you
can just add them to your program without caring how they
work, all you needs to know is what these functions do.
C++ built in functions are commonly required functions
grouped together and stored in what is called a library.
This library function is present on the disk and is written for
us by people who had written compiler for us.
The standard c++ library is a collection of pre defined
function and other program element which are accessed
through header files.
The header files contains the function prototype for all the
function used in the program and thus we need to include
those whenever a particular function is referred in side a
program.
Ex: mathematic functions, string handling functions,
function used for dynamic memory allocation etc.
User defined functions:-
User-defined functions are small programs that
you can be written to perform an operation.
These functions are created by users. You can
then use that function wherever and whenever
required in your program like in built functions.
In order to make use of a user-defined function,
we need to establish three elements that are
related to function:
a. Function declaration or function prototype.
b. Function definition.
c. Function call.



Like variables,all functions must be declared,before they are invoked.
A function declarartion is constists of four parts:-
return type.
Function name.
Argument list.
Semicolon.

declaration statement:
return type function-name(argument-list);
ex: void addition(void);
int addition(int x,int y,int z);
float addition(int x,float y);


Function declaration is known as Function prototyping .

Function prototyping is one of the major improvements added to c++
functions.



Function declaration or function prototype
The prototype describe the function interface to the
compiler by giving details such as the number and
type of arguments and the type of return values.
When a function is called, the compiler uses this
prototype to ensure that proper arguments passed,
and the return value is treated correctly .
If there is mismatch the compiler points it out
immediately.
In general we either include or exclude the variable
names in the argument list of prototypes.
The variable name in the prototype just act as place
holders and,therefore,if name are used in the
function call or function definition.
We can also declare a function with an empty
argument list.
E.g.:Void addition();
Category of function prototype.
A function depends on whether arguments
are present or not and whether a value is
return or not. Depending on this, the
functions are divide into following categories:-
Function with no arguments and no return
type.
Function with arguments and no return type.
Function with arguments and a return type.
Function with no arguments but a return type.



Function with no arguments and no return type.

When a function has no argument, it does not
receive any data from the calling function.
Similarly when it does not return a value, the
calling function does not receive any data
from the called function.
In fact there is no data transferred between
the calling function and the called function,
but there is only transfer of controls occurs.
Ex: void addition (void);
Or we can write it as
void addition ();
Function with arguments and no return type.

We could make the calling function to read
data from the terminals and pass it on to the
called function. This approach is the best one
because the calling function can check for the
validity of data, if necessary before it is
handed over to the called function.
Eg:- void addition(int x,int y);
Function with arguments and a return type.

Sometimes it may happens that different
programs may required different output
format for display of result. This short comings
can be overcome by handling over the result
of a function to its calling function where the
result value can be used as required by the
program.
Eg:
int addition(int x,int y);
Function with no arguments but a return type.

There could be occasions where we may need
to design function that may not take any
arguments but returns a value to the calling
function.
Eg:
int addition();
Function definition.
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{
body of the function ;
Return_statement;
}

Example 1:
void addition(int x,int y)
{
cout<<x+y;
}
A C++ function definition consists of a function header and a
function body.


Example 2:
int addition(int x,int y)
{
return(x+y);
}
Here are all the parts of a function:
Return Type: A function may return a value. The return_type is the
data type of the value the function returns. Some functions
perform the desired operations without returning a value. In this
case, the return_type is the keyword void.

Function Name: This is the actual name of the function. The
function name and the parameter list together constitute the
function signature.

Parameters: A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred to
as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no
parameters.

Function Body: The function body contains a collection of
statements that define what the function does.

Function call.
While creating a C++ function, you give a definition of
what the function has to do. To use a function, you will
have to call or invoke that function into main as
compiler is capable of reading the main function only .
When a program calls a function, program control is
transferred to the called function. A called function
performs defined task and when its return statement is
executed or when its function-ending closing brace is
reached, it returns program control back to the main
program.
To call a function you simply need to pass the required
parameters along with function name and if function
returns a value then you can store returned value.

Example of user defined function:
#include <iostream>
int addition(int num1, int num2);//declaration/protype of function
int main () //here main() is the calling function
{
int a = 100; int b = 200 ret; // here a,b local variable declaration:
ret = addition(a, b); // calling the addition function (actual argument)
cout << "Max value is : " << ret << endl;
getch();
}
int addition(int num1, int num2)//here addition called is function(formal argument )
{
int r;
r=num1+num2;
return(r);
}
The use of argument list:
The argument list is used to pass values to the
called function from the calling function .
Sq(a);
All the variables in the argument list must be
declared with their type immediately after the
function header;
Argument to a function are usually passed in
two ways
Call by value.
Call by reference
Function call by value:
When ever we called a function and passed values
of variables to the called function, such function
calls are called call by value with this method,
change made to the parameters of the function
have no effect on the variables in the calling
function.

Function call by reference:
call by reference is a method in which the address
of each argument is passed to the function. By
this method, the change made to the parameters
of the function will affect the variable in the
calling function.

Function overloading
A significant addition made to the
capabilities of function in C++ is that of
function overloading.with this facility we
can have multiple functions with the same
name.
E.g.: int square(int)
float square(float)
long square(long)
Here the program contain three functions by
name square.so this program,the functions
called square is overloaded.
During the compilation make the selection
by looking at the types of perimeters that
are passed to the function when it is called.
The minimum requirement for function
overloading is that the function must differ
in type,number or sequences of
parameters.
Two function of same name cannot be
overloaded if their return type alone are
different.
Inline functions
As all the calls to the function cause the same code to be
executed; it involves an overhead in terms of the time
taken on passing values, passing control, returning values
and returning controls.
In C++ it is possible to save execution time by declaring
the function inline.
Inline function is a function that is expanded at the place
where the function is called.(i.e whenever the function is
called from somewhere else in the program,the entire
code for the function is actually expanded at the place
where the function is called.)
Inline function-header
{

Function body
}

Recursion.

In c it is possible for a function to call itself.if
the statement in the body of a function calls
the function itself then the function is known as
recursive function.
String handling Function
A Function is a self-contained block of statements that
perform a coherent task of some kind. Every C++ program
can be thought of as a collection of these functions.
Function name Use
Strlen Finds length of a string
Strwr Converts a string to lowercase
Strupr Converts a string to uppercase
Strcat Appends one string at the end of another
Strcpy Copies a string into another
Strcmp Compares two strings.
Strrev Reverses string
Dynamic memory allocation.

Dynamic memory allocation allows the user of
the program to instruct the program, how
much memory he needs, during run time...
There are 4 dynamic memory allocation
function.
malloc().
Free().
realloc().
calloc().
malloc() a malloc function returns a pointer
to the 1
st
byte of a region of memory of size
specified. This memory has get allocated from
the heap of memory. If there is insufficient
memory in the heap to satisfied the request
then the malloc returns a null pointer. It is
always important to verify that the return
value is not null before attempting to use it.
Attempting to use a null pointer will usually
result in system crash.
Syntax:
Void *malloc(size s);
Free() the free function returns the memory
pointer to the memory location in heap to the
operating system so that operating system
makes the memory available for future
allocation.
Free function is used with one of the dynamic
allocation system function(either malloc or
calloc).
Syntax:-
free();
calloc() the calloc function allocate memory
when there is a need to assign equal amount
of memory size for n numbers of elements. i.e
calloc allocates sufficient memory for an array
of n number of elements having size.
Calloc function returns a pointer to the first
byte of the allocated region if there is not
enough memory to satisfied, a null pointer is
returned.
it is always important to verify that return
value is not null before attempting to use it.
Math functions.
C++ mathematical operations are a group of functions in
the standard <math.h> file library of the C++ programming
language implementing basic mathematical functions. All
functions use floating point numbers in one manner or another.
Some of the mathematical functions are given bellow:-
Math functions descriptions
int abs (int n); Returns the absolute value of parameter n.
double sqrt (double x); Returns the square root of x.
double pow(double x, double y); it returns the result of raising x to the power y.
double cos(double x); Returns the cosine of a radian angle x.
double sin(double x); Returns the sine of a radian angle x.
double log (double x); Returns the natural logarithm of x.
The end of unit- 4

Vous aimerez peut-être aussi