C++ Chapter 3 Manfg
C++ Chapter 3 Manfg
Function in C++
1.1. Introduction
A complex problem may be decomposed in to a small or easily manageable parts or modules called
Functions. A function provides a convenient way of packaging a computational recipe, so that it can be used
as often as required. Therefore, a function is a block of code designed to tackle a specific problem. Or
function is a group of statement that is executed when it is called from some point of the program. Functions
are very useful to read, write, debug and modify complex programs. They can also be easily incorporated in
the main program. In C++, the main()itself is a function that means the main function is invoking the other
function to perform various tasks
The main advantages of using a function are:
Divide and conquer
Construct a program from smaller pieces or components
Each piece more manageable than the original program
Software reusability
Use existing functions as building blocks for new programs
Let’s other people use algorithms you’ve implemented
Maintainability: To change the algorithm, just change the function (vschanging it everywhere you
ever used it)
Readability: sqrt(5) is clearer than copy-pasting in an algorithm to compute the square root
Different people can work on different functions simultaneously.
While working on one function, you can focus on just that part of the program and construct it, debug
it, and perfect it.
In C++, the functions may or may not take some formal arguments for calling a portion of the program. The
function may or may not transfer back, values to a called function block.
1|Page
2. Function names are made up and assigned by the programmer following the same rules that apply to
naming variables. They can contain up to 32 characters, they must begin with a letter, and they can
consist of letters, numbers, and the
underscore (_) character.
3. All function names have one set of parenthesis immediately following them. This helps you (and C++
compiler) differentiate them from variables.
4. The body of each function, starting immediately after parenthesis of the function name, must be enclosed
by braces{ and }.
1.3. Types of Functions
There are two types of functions:
A. Pre-defined (standard) functions
B. User-defined functions.
A. Predefined functions
Predefined functions are functions that are built into C++ Language to perform some standard operations.
The functions that are standalone used for general purposes and that are not depended on any classes are
stored in the Standard Function Library. Predefined functions in the Standard Function Library are listed
based on different categories. For example:
2|Page
than x: ceil(56.34)=57.0
cos(x) Return the cosine of angle x: cos(0.0)=1.0 double double
exp(x) Returns ex, where e=2.718: exp(1.0)=2.71828 double double
fabs(x) Returns the absolute value of its argument: fabs(- double double
5.67)=5.67
floor(x) Returns the largest whole number that is not double double
greater than x: floor(45.67)=45.00
pow(x, y) Return xy:if x is negative, y must be a whole double double
number: pow (0.16, 0.5)=0.4
tolower(x) Returns the lowercase value of x, if x is int int
uppercase; otherwise, returns x.
toupper(x) Returns the uppercase value of x, if x is int int
lowercase; otherwise, returns x.
B. User-defined Functions
C++ allows programmers to define their own functions. For example, the following is a definition of a
function which given the co-ordinates of appoint (x,y) will return its distance from the origin.
A function definition has a name, a parentheses pair containing zero or more parameters and a body. For each
parameter, there should be a corresponding declaration that occurs before the body. Any parameter not
declared is taken to be an int by default. It is good programming practice to declare all parameters. The
general format/syntax of the function definition is given below.
3|Page
a) Function return type –In place of this we write the type of value return by a function to the calling
portion of the program. Any of the basic data types such as int, float, char etc.can be used. If a function
returns nothing to the calling portion of the program, then we write void in place of function return type. E.g.
Note: the return type value must be same as function return type. But if function return type is void no need
of return statement.
int fun-name(type1 arg1, type2 arg2, …) { floatfun-name (type1 arg1, type2 arg2, …) {
___________ ____________ b)
___________ ____________
return (int type value); return (float type value); Function
} } name –
The
function name can be any name conforming to the syntax rules of the variables/identifier. Normally, a
function name is made relevant to the function operation, as it will be easy to keep a track of it, whenever a
transfer of similar functions is used in the main program.
e.g.counter (); square (); display_value (); and output ();
c) Data type and argument (parameter lists) – Parameter lists are a set of zero or more typed identifiers
used for passing values to and from the function. The data type must be listed explicitly for each argument.
Argument is a data passed from a program to a function. For example, write a function which calculate sum
of two integer type numbers.
Solution:
d) Function Body –a statement or a block of statements is enclosed between two braces {and}.
e) Return Statement- return is a reserve word that is used to terminate function and return a values to its
caller. The general syntax of return statement is:
return (value); or return value
The value can be expressions and also possible skip the value part i.e. return;
e.g. return (a-b);
return (j--);
return;
4|Page
Note: a function can also have more than one return statement.
e.g. int smaller (int a, intb){
if(a<b) return (a);
else return (b); }
The declaration called the function prototype, tells the computer the name, return type, and parameters of the
function. The prototype describes the function interface to the compiler by giving details such as the number
and type of the of argument and the type of return values. Note that in C++ prototype is must when the
function definition is coming after the main function otherwise no need of declaring the function prototype.
It’s placed after the pre-processor directive and before main () function. The general syntax of prototype
declaration is:
Return_type function_name (parameter_list);
The function return type. This specifies the type of value the function returns. A function which
returns nothing should have a return type void.
The function name. this is simply a unique identifier
The function parameters (also called its signature). This is a set of zero or more typed identifiers
used for passing values to and from the function.
e.g. intmul (int a, int b);
void fac(float x, float y);
intmul(inta,b);// this is illegal
In prototype declaration the name of argument is optional but the type is must. If the return type is void and
suppose we are not passing any variable to function.
e.g. intmul(int , int);
void mul();
void mul(void);
1.4.3. Calling the Function
Using a function involves ‘calling’ it. Calling a function means making the instruction of the function to be
executed. A function call consists of the function name followed by the call operator brackets ‘()’, inside
which zero or more comma-separated arguments appear. The number and type of arguments should match
the number of function parameters. Each argument is an expression whose type should match the type of the
corresponding parameter in the function interface. When a function call is executed, the arguments are first
evaluated and their resulting values are assigned to the corresponding parameters. The function body is then
5|Page
executed. Finally, the return value (if any) is passed to the caller. A function call in C++ is like a detour on a
highway. Imagine that you are traveling along the “road” of the primary function called main(). When you
run into a function-calling statement, you must temporarily leave the main() function and execute the
function that was called. After that function finishes (its return statement is reached), program control returns
to main(). In other words, when you finish a detour, you return to the “main” route and continue the trip.
Control continues as main() calls other functions. The general syntax of calling a function is as follows if
function return type is void:
Functionname(parameter name);
If function returnsint, float or any other type value then we have to assign the call to a same type value like:
Datatype variable name=functionname (parameter name);
e.g. make (); sum (x, y); int m=mul (x, y, z);
Example
A program to demonstrate a function, function calling and function definition in C++.
#include<iostream.h>
void display(void); //function prototype
Void main(void)
{
display(); //function calling
}
void display(void) //function definition
{
Cout<<”This is a test program\n”;
Cout<<”for demonstrating a function call\n”;
Cout<<”in C++\n”;}
#include<iostream.h>
void display(void) //function definition
{
Cout<<”This is a test program\n”;
Cout<<”for demonstrating a function call\n”;
Cout<<”in C++\n”;
void main(void)
{
display(); //function calling
}
Another example:
#include<iostream.h>
#include<conio.h>
void starLine(); //prototype of the function with a name starLine
int main()
{
starLine(); //Calling the function with a name starLine
cout<< “Data type Range” <<endl;
starLine();
cout<< “char -128 to 127” <<endl<<“short -32,768 to 32,767”
<<“\n int system dependent” << “\n long -2,147,483,648 to 2,147,483,647” <<endl;
starLine();
return 0;
}
7|Page
#.....
void Foo(intnum)
{ num = 0;
cout<< “num= ”<<num<< “ \n”;
}
int main(void)
{ int x = 10;
Foo(x);
cout<< “x = ”<<x<< “\n”;
getch();
return 0;
}
The single parameter of Foo is a value parameter. As far as this function is concerned, num behaves just like
a local variable inside the function. When the function is called and x passed to it, num receives a copy of the
value of x. As a result, although num is set to 0 by the function, this does not affect x. the program produces
the following output: num = 0
x = 10
Passing arguments in this way, where the function creates copies of the arguments passed to it is called
passing by value.
8|Page
The parameter of Foo is a reference parameter. Num will correspond to x for this specific program as it x is
sent by its reference and not its value. Any change made on num will be effected to x. Thus, the program
produces the following output: num = 0
x=0
Suppose you have pairs of numbers in your program and you want to be sure that the smaller one always
precedes the larger one. To do this, you call a function, order(), which checks two numbers passed to it by
reference and swaps the originals if the first is larger than the second.
#.......
#.......
void order(int&, int&);
intmain()
{
int n1 = 99, n2=11;
int n3 = 22, n4=88;
order(n1,n2);
order(n3,n4);
cout<< “n1=”<<n1<<endl;
cout<< “n2=”<<n2<<endl;
cout<< “n3=”<<n3<<endl;
cout<< “n4=”<<n4<<endl;
return 0; }
void order(int& num1,int & num2)
{
if(num1 > num2)
{
int temp=num1;
num1 = num2;
num2 = temp;
}
}
In main() there are two pairs of numbers-the first pair is not ordered and the second pair is ordered. The
order() function is called once for each pair, and then all the numbers are printed out. The output revels that
the first pair has been swapped while the second pair has not. Here it is:
n1 = 11
n2 = 99
n3 = 22
n4 = 88
In the order() function the first variable is called num1 and the second is num2. If num1 is greater than num2,
the function stores num1 in temp, puts num2 in num1, and finally puts temp back in num2. Using reference
arguments in this way is a sort of remote control operation. The calling program tells the function what
9|Page
variables in the calling program to operate on, and the function modifies these variables without ever
knowing their real names.
1.6. Global versus local variables
Everything defined at the program scope level (outside functions) is said to have a global scope, meaning
that the entire program knows each variable and has the capability to change any of them. Eg.
Because a local scope overrides the global scope, having a local variable with the same name as a global
variable makes the latter inaccessible to the local scope. Eg
int num1;
10 | P a g e
void fun1(int num1)
{
//…
}
The global num1 is inaccessible inside fun1(), because it is overridden by the local num1 parameter. This
problem is overcome using the scope operator ‘::’ which takes a global entity as argument.
int num1 = 2;
void fun1(int num1)
{
//…
num1=33;
cout<<num1; // the out put will be 33
cout<<::num1; //the out put will be 2 which is the global
if(::num1 != 0)//refers to global num1
//…
}
1.8. Automatic versus static variables
The terms automatic and static describe what happens to local variables when a function returns to the calling
procedure. By default, all local variables are automatic, meaning that they are erased when their function
ends. You can designate a variable as automatic by prefixing its definition with the term auto. For example,
The two statements after main()’s opening brace declared automatic local variables:
main()
{
inti;
auto float x;
…
}
The opposite of an automatic is a static variable. All global variables are static and, as mentioned, all static
variables retain their values. Therefore, if a local variable is static, it too retains its value when its function
ends-in case this function is called a second time. To declare a variable as static, place the static keyword in
11 | P a g e
front of the variable when you define it. Static variables can be declared and initialized within the function,
but the initialization will be executed only once during the first call. If static variables are not declared
explicitly, they will be declared to 0 automatically. Eg.
void my_fun()
{
static intnum;
static int count = 2;
count=count*5;
num=num+4;
}
In the above example: During the first call of the function my_fun(), the static variable count will be
initialized to 2 and will be multiplied by 5 at line three to have the value 10. During the second call of the
same function count will have 10 and will be multiplied by 5. During the first call of the function my_fun(),
the static variable num will be initialized to 0 (as it is not explicitly initialized) and 4 will be added to it at
line four to have the value 4. During the second call of the same function num will have 4 and 4 will be add
to it again.
N.B. if local variables are static, their values remain in case the function is called again.
1.9. Inline functions
Suppose that a program frequently requires finding the absolute value of an integer quantity. For a value
denoted by n, this may be expressed as:
(n >0 ? n : -n)
However, instead of replicating this expression in many places in the program, it is better to define it as a
function:
intAbs(int n)
{
return n>0 ? n : -n;
}
The function version has a number of advantages.
It leads to a more readable program.
It is reusable.
12 | P a g e
The disadvantage of the function version, however is that
Its frequent use can lead to considerable performance penalty due to overheads associated with
calling a function.
The overhead can be avoided by defining Abs as an inline function.
inline intAbs(int n)
{
Return n>0 ? n : -n;
}
The effect of this is that when Abs is called, the compiler, instead of generating code to call Abs, expands the
program body and substitutes the body of Abs in place of the call. While essentially the same computation is
performed, no function call is involved and hence no stack frame is allocated. The "inline" keyword is
merely a hint to the compiler or development environment. Not every function can be inlined. Some typical
reasons why inlining is sometimes not done include:
Another good reason to inline is that you can sometimes speed up your program by inlining the right
function. Instead of calling the function every time it is invoked, the compiler will replace the function call
with a copy of the function body. If it's a small function which gets called a lot, this can sometimes speed
things up. Most of the advantage of inline functions comes from avoiding the overhead of calling an actual
function. Such overhead includes saving registers, setting up stack frames, and so on. But with large
functions the overhead becomes less important. Concerning inline functions, the compiler is free to decide
whether a function qualifies to be an inline function. If the inline function is found to have larger chunk
(amount) of code, it will not be treated as an inline function, but as like other normal functions. Then, Why
not inline everything? :Since the compiler will copy the entire function body every time the function is
called, if it is a large function (more than three or four lines), inlining can increase the size of your executable
program significantly.
C++ has two capabilities that regular C doesn’t have. Default arguments and function overloading.
1.10.1. Default arguments
13 | P a g e
Default argument is a programming convenience which removes the burden of having to specify argument
values for all function parameters.
Eg. You might pass a function an error message that is stored in a character array, and the function
displays the error for a certain period of time. The prototype for such a function can be this: Void
pr_msg(char note[]);
Therefore, to request that pr_msg() display the line ‘Turn printer on’, you call it this way:
As you write more of the program, you begin to realize that you are displaying one message-for instance, the
‘Turn printer on’ msg-more often than any other message. Instead of calling the function over and over,
typing the same message each time, you can set up the prototype for pr_msg() so that it defaults to the ‘turn
printer on’ message in this way:
This makes your programming job easier. Because you would usually want pr_msg() to display ‘turn printer
on’, the default argument list takes care of the message and you don’t have to pass the message when you
call the function. For functions having more than one argument with default, the parameters with possible
default value should be declared in the right side of the function definition and prototype.
14 | P a g e
Add_Display(a,b); //will print 120 (ie 40+50+30)
Add_Display(a); //will print 90 (ie 40+20+30)
Add_Display(); //will print 60 (ie 10+20+30)
Mult_Display(a,b) //will print 2000 (40*50)
Mult_Display(a) //will print 2800 (40*70)
//Mult_Display() //is invalid as there is no default for x
getch();
}
//the following function definition is invalid as z is a parameter without a default and written after y
//parameters with default should always be at the right side of function declaration
void Mult_Dispaly (int x, int y=70, int z)
{
cout<< (x*y*z);
}
//thus the following function definition will be correct
void Mult_Dispaly (int x, int z, int y=70)
{
cout<< (x*y*z);
}
1.10.2. Overloaded Functions
Unlike C, C++ lets you have more than one function with the same name. In other words, you can have three
functions called abs() in the same program. Functions with the same name are called overloaded functions.
C++ requires that each overloaded functions differ in its argument list. Overloaded functions enable you to
have similar functions that work on different types of data. Suppose that you wrote a function that returned
the absolute value of whatever number you passed to it:
intiabs(inti)
{ if(i<0)
Return (i*-1);
else
Return (i);
15 | P a g e
}
float fabs(float x)
{ if(x<0.0)
Return (x * -1.0);
else
Return (x);
}
Without using overloading, you have to call the function as:
intans = iabs(weight);//for int arguments
float ans = fabs(weight);//for float arguments
But with overloading, the above code can be used as:
intabs(inti);
float abs(float x);
intmain()
{
…
ians = abs(i);//calling abs with int arguments
fans = abs(p);//calling abs with float arguments
…
}
intabs(inti)
{
if(i<0)
Return i*-1;
else
Return I;
}
float abs(flaot x)
{
if(x<0.0)
16 | P a g e
Return x*-1.0;
else
Return x;
}
N.B: if two or more functions differ only in their return types, C++ can’t overload them. Two or more
functions that differ only in their return types must have different names and can’t be overloaded
1.11. Recursion
A function which calls itself is said to be recursive. Recursion is a general programming technique applicable
to problems which can be defined interms of themselves. Take the factorial problem, for instance which is
defined as:
- factorial of 0 is 1
The second line clearly indicates that factorial is defined in terms of itself and hence can be expressed as a
recursive function.
intFactorial(unsigned int n )
{
return n = = 0 ?1 : n * factrial(n-1);
}
For n set to 4, the following figure shows the recursive call:
The stack frames for these calls appear sequentially on the runtime stack, one after the other.
A recursive function must have at least one termination condition which can be satisfied. Otherwise, the
function will call itself indefinitely until the runtime stack overflows. The three necessary components in a
recursive method are:
17 | P a g e
3. A recursive call(s) that continues the recursion
let us implement two more mathematical functions using recursion
e.g the following function computes the sum of the first N positive integers 1,2,…,N. Notice how the
function includes the three necessary components of a recursive method.
intsum(int N)
{
if(N==1)
return 1;
else
return N+sum(N);
}
The last method computes the exponentiation Anwhere A is a real number and N is a positive integer. This
time, we have to pass two arguments. A and N. the value of A will not change in the calls, but the value of N
is decremented after each recursive call.
float expo(float A, int N)
{
if(N==1)
return A;
else
return A * expo(A,N-1);
}
Try to use a recursive function call to solve the Fibonacci series. The Fibonacci series is: 0,1,1,2,3,5,8,13,21,
…
the recursive definition of the Fibonacci series is as follows:
Fibonacci (0) =0
Fibonacci (1) =1
Fibonacci (n) =Fibonacci (n-1) +Fibonacci (n-2);
18 | P a g e
Both iteration and recursion are based on control structure. Iteration uses a repetition structure (such
as for, while, do…while) and recursive uses a selection structure (if, if else or switch).
Both iteration and recursive can execute infinitely-an infinite loop occurs with iteration if the loop
continuation test become false and infinite recursion occurs id the recursion step doesn’t reduce the
problem in a manner that coverage on a base case.
Recursion has disadvantage as well. It repeatedly invokes the mechanism, and consequently the
overhead of method calls. This can be costly in both processor time and memory space. Each
recursive call creates another copy of the method (actually, only the function’s variables); this
consumes considerable memory.
19 | P a g e