Unit III: Periods: 10
Introduction to Function,
Function Prototyping,
Call by Value & Call by reference,
Inline function,
default arguments,
Function Overloading,
Library Functions
C++ Functions
A function groups a number of program statements into a unit and gives it a name. This unit can then be
invoked from other parts of the program. The function’s code is stored in only one place in memory, even
though the function is executed many times in the course of the program’s execution. Functions help to
reduce the program size when same set of instructions are to be executed again and again. A general
function consists of three parts, namely, function declaration (or prototype), function definition and
function call.
Function declaration — prototype:
A function has to be declared before using it, in a manner similar to variables and constants. A function
declaration tells the compiler about a function's name, return type, and parameters and how to call the
function. The general form of a C++ function declaration is as follows:
return_type function_name( parameter list );
Function definition
The function definition is the actual body of the function. The function definition consists of two parts
namely, function header and function body.
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{ body of the function }
Here, 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.
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.
Calling a Function
To use a function, you will have to call or invoke that function. 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.
int no, f;
cout<<”enter the positive number:-“;
cin>>no;
f=factorial(no); //function call cout<<”\
nThe factorial of a number”<<no<<”is”<<f; return 0;
}
int factorial(int n) //function definition
{ int i , fact=1;
for(i=1;i<=n;i++){
fact=fact*i;
}
return fact;
}
A c++ program calculating factorial of a number using functions
#include<iostream.h>
#include<conio.h>
int factorial(int n); //function declaration int
main(){
4.1.1 Call by address(pass by address)
Instead of passing value address are passed. Function operates on addresses rather than values.
The formal arguments are pointers to the actual argument.hence,changes made in the arguments
are permanents.
Program - Write a program to swap two number
#include<iostream.h>
void main()
{
int x,y;
void swap(int * ,int *);
cout<<”enter value of x and y”;
cin>>x>>y;
swap(&x, &y);
cout<<”x=”<<x<<”y=”<<y;
}
void swap(int *p, int *q)
{
int k;
k=*p; *p=*q; *q=k;
}
4.1.2 Call by reference(pass by reference)
Program - Write a program to swap two value
#include<iostrea
m.h> void
main()
{
int x,y;
void swap(int & , int &);
cout<<”enter value of x
and y”; cin>>x>>y;
swap(x, y);
cout<<”x=”<<x<<”y=”<
<y;
}
void swap(int &p, int &q)
{
i
n
t
k
;
k
=
p
;
p
=
q
;
q
=
k
;
}
Inline Functions
An inline function is a function that is expanded inline at the point at which it is invoked,
instead of actually being called. The reason that inline functions are an important addition to
C++ is that they allow you to create very efficient code. Each time a normal function is
called, a significant amount of overhead is generated by the calling and return mechanism.
Typically, arguments are pushed onto the stack and various registers are saved when a
function is called, and then restored when the function returns. The trouble is that these
instructions take time. However, when a function is expanded inline, none of those
operations occur. Although expanding function calls in line can produce faster run times, it
can also result in larger code size because of duplicated code. For this reason, it is best to
inline only very small functions. inline is actually just a request, not a command, to the
compiler. The compiler can choose to ignore it. Also, some compilers may not inline all
types of functions. If a function cannot be inlined, it will simply be called as a normal
function.
A function can be defined as an inline function by prefixing the keyword inline to the
function header as given below:
inline function header
{ function body
}
// A program illustrating inline
function #include<iostream.h>
#include<conio.h>
inline int max(int x,
int y){ if(x>y)
return x;
else
return
y;
int
main( )
{ int a,b;
cout<<”enter two
numbers”; cin>>a>>b;
cout << "The max is: " <<max(a,,b)
<< endl; return 0;
}
Macros Vs inline functions
Preprocessor macros are just substitution patterns applied to your code. They can be used
almost anywhere in your code because they are replaced with their expansions before any
compilation starts. Inline functions are actual functions whose body is directly injected into
their call site. They can only be used where a function call is appropriate.
inline functions are similar to macros (because the function code is expanded at the point of
the call at compile time), inline functions are parsed by the compiler, whereas macros are
expanded by the preprocessor. As a result, there are several important differences:
Inline functions follow all the protocols of type safety enforced on normal functions.
Inline functions are specified using the same syntax as any other function except
that they include the inline keyword in the function declaration.
Expressions passed as arguments to inline functions are evaluated once.
In some cases, expressions passed as arguments to macros can be evaluated more than
once.
macros are expanded at pre-compile time, you cannot use them for debugging, but
you can use inline functions.
Reference variable
A reference variable is an alias, that is, another name for an already existing variable. Once
a reference is initialized with a variable, either the variable name or the reference name may
be used to refer to the variable. To declare a reference variable or parameter, precede the
variable's name with the &.The syntax for declaring a reference variable is:
datatype &Ref = variable name;
Example:
int main(){
int var1=10; //declaring simple
variable int & var2=var1; //declaring
reference variable cout<<“\n value of var2
=” << var2;
return 0;
var2 is a reference variable to var1.Hence, var2 is an alternate name to var1.This code prints
the value of var2 exactly as that of var1.
Call by reference
Arguments can be passed to functions in one of two ways: using call-by-value or call-by-
reference. When using call-by-value, a copy of the argument is passed to the function. Call-
by-reference passes the address of the argument to the function. By default, C++ uses call-
by-value.
Provision of the reference variables in c++ permits us to pass parameter to the functions by
reference. When we pass arguments by reference, the formal arguments in the called
function become aliases to the actual arguments in the calling function. This means that
when the function is working with its own arguments, it is actually working on the original
data.
Example
#include
<iostream.h>
#include<conio.h>
void swap(int &x, int &y); // function
declaration int main (){
int a = 10, b=20;
cout << "Before swapping”<<endl;
cout<< “value of a :" << a <<” value of b :" <<
b << endl; swap(a, b); //calling a function
to swap the values. cout << "After
swapping”<<endl;
cout<<” value of a :" << a<< “value of b :" <<
b << endl; return 0;
void swap(int &x, int &y) { //function definition to swap the
values. int temp;
temp =
x; x =
y;
y = temp;
}
Output:
Before swapping value of a:10 value of
b:20 After swapping value of a:20 value of
b:10
Function Overloading
Function overloading is the process of using the same name for two or more functions. Each redefinition
of the function must use either different types of parameters or a different number of parameters. It is only
through these differences that the compiler knows which function to call in any given situation.
Overloaded functions can help reduce the complexity of a program by allowing related operations to be
referred to by the same name. To overload a function, simply declare and define all required versions. The
compiler will automatically select the correct version based upon the number and/or type of the arguments
used to call the function. Two functions differing only in their return types cannot be overloaded.
Example #include<iostream.h>
#include<conio.h>
int sum(int p,int q,int r); double
sum(int l,double m); float sum(float
p,float q)
int main(){
cout<<”sum=”<< sum(11,22,33); //calls func1
cout<<”sum=”<< sum(10,15.5); //calls func2
cout<<”sum=”<< sum(13.5,12.5); //calls func3 return 0;
int sum(int p,int q,int r){ //func1
return(a+b+c);
double sum(int l,double m){ //func2
return(l+m);
float sum(float p,float q){ //func3
return(p+q);
4.1 Library function
a) ceil, ceill and floor, floor1
The function ceil, ceill round up given float number.
The function floor,floor1 round down float number.
They are defined in math.h header
file #include<iostream.h>
#include<math.h>
void main()
{
float num=3.2;
float d,u;
d=float(num);
u=ceil(num);
cout<<num<<u<<d;
}
b) Modf and modf1
The function modf breaks double into integer and fraction elements
The function modf1 breaks long double into integer and fraction
elements. void main()
{
double f,I;
double num=211.57;
f=modf(num,&i);
cout<<num<<i<<f;
}
c) abs, fabs and labs
The function abs() returns the absolute value of integer.
The fabs() returns the absolute value of a floating point number.
The labs() returns the absolute value of a long
number. Declaration:
Int abs(int n);
double fabs(double n);
long int labs(long int n);
d) norm
The function is defined in complex.h header file and it is used to calculate the square of
the absolute value.
Program
Write a program to calculate the square of the complex number using norm() function.
#include<iostream.h>
#include<complex.h
> #include<conio.h>
int main(0
{
double x=-
12.5;
cout<<norm(x);
return 0;
}
e) complex(), real(), imag() and conj()
complex(): - is defined in complex.h header file & it create complex numbers.
real() :- it returns real part of the complex number .
imag() ;- it returns imaginary part of the complex number.
Conj() :- it returns complex conjugate of a complex
number. Program
Write a program to addition, subtraction and multiplication of two complex
number. #include<iostream.h>
#include<conio.h>
class complex
{
public:
int
real,imag;
void in()
{
cout<<"enter real part :";
cin>>real;
cout<<"enter imaginary part:";
cin>>imag;
}
};
void main()
{
clrscr();
complex a,b,c;
a.in();
b. in();
cout<<"\n addition of two complex number :";
c.real=a.real+b.real;
c. imag=a.imag+b.imag;
cout<<c.real<<"+"<<c.imag<<"i"
;
cout<<"\n subtraction of two complex
number :"; c.real=a.real-b.real;
c.imag=a.imag-b.imag;
cout<<c.real<<"+"<<c.imag<<"i";
cout<<"\n multiplicaton of two
complex number :";
c.real=a.real*b.real-a.imag*b.imag;
c.imag=a.imag*b.real+a.real*b.imag;
cout<<c.real<<"+"<<c.imag<<"i";
getch();
}