You are on page 1of 9

C++ Programming 41 Functions

Chapter-4

Functions
Function is a program segment or a sub program (or a module) that performs
a specific and well-defined task. It reduces the complexity of the program.

A function is an independent program that can be used by the main program


or other sub programs. A sub program receives the value from the calling function,
perform the task and return the results to the calling function.
C++ functions are classified into two categories
 Built in functions or library functions
 User defined functions
Built-in functions are the predefined functions which are made available as part of
C++ library. They can be used by any programmer.
e.g: sqrt( ), pow( ),abs( ), sin( ), cos( ) etc are defined under the header file math.h

strcpy( ), strlen( ), strupr( ) etc are defined under the header file string.h
User defined functions: C++ allows programmers to define our own function
within a program. A program may contain one or more functions. The execution
always starts from the main; all other functions are invoked from the main.

Function definition: Function definition is writing the actual code for the function.
The general format of the function definition is as follows

Return-Type function-name (parameter list) Function Header


{
Local-variable declaration;
Statement 1;
: Function Body
Statement n;
return (value);
}

Return-Type  the data type of the return value of the function. If nothing is returned
the data type is void.
Function-name a valid identifier
Parameter list  list of variable that receives value from calling function.
return() is a keyword that returns a value from sub function to calling function.

The first line containing of return-type, function-name and parameter list is


called as the function header. The local-variable declaration part and the set of
statements enclosed within curly braces is referred to as the function body.

A function, which is defined, can not be executed by itself. It has to be invoked


by another function. It can be main() or any other function. A function which
invokes another function is called calling function and the function which is invoked
is termed as called function.

Mahesha. S SSC, Tumkur Cell : 9886044689


C++ Programming 42 Functions

Function prototype:
The function prototype is the function declaration that provides the following
information to the compiler.

1. The return type of function.


2. The function name.
3. Argument list, which are passed to the called function.

The general syntax of function prototype is:


Return-type function-name (argument-list);
If no arguments specified in the argument list C++ assumes it as void and if
no return type is specified, the default return type is ‘void’.
e.g. int product( int x, int y);
float avg(float a, float b);
void swap(int, int);

The return statement: return is a key word used to send the o/p of the function
back to the calling function. It is a means of communication from the calling function
to the called function. The constant or variable or expression will return the value to
the calling function after processing.
Syntax: 1. return;
2. return (expression);
The first return statement does not return any value. It simply returns control
to the point from where it was called.
The second return statement returns the value of the expression.
Note: A function can have multiple return statements, but at any given time only one return
statement will be executed.

P32. WAP to find the factorial of a given number.


Actual parameters and Formal parameters: Arguments or parameters are the
variables used in a program.
Actual parameters: The variables used in the calling function are called Actual
parameters, since they are accepted in the main function (calling function).
Formal parameters: The variables used in the function definition are called Formal
parameters, since they are not the accepted values. They have a copy of actual
parameters.
Note:
1. There is a one to one correspondence between the actual parameters and
the formal parameters i.e. the number of actual parameters is equal to
the no of formal parameters.
2. Order of actual parameters matches with the order of formal parameters.
3. The data type of actual parameters matches with the data type of formal
parameters.

Parameter passing techniques: The communication between calling function and


called function is done through parameters. There are 3 types of parameter passing
techniques.
1) Call by value (pass by value)
2) Call by address (pass by address using pointers)
3) Call by reference (pass by reference using references)

Mahesha. S SSC, Tumkur Cell : 9886044689


C++ Programming 43 Functions

Call by value
In this method the copy of the value of actual parameters is passed to the
function. This mechanism of data transfer between the actual and formal parameters
is called call by value. The current value of actual parameter becomes the initial value
of formal parameters. Any change made to the formal parameters will not change
the value of actual parameters.

P33. A program to illustrate the function using call by value.

Call by address (pass by address): In this method instead of passing the values,
the memory address of the corresponding arguments is passed. Hence the receiving
parameter (formal parameter) should be a pointer. Hence any change made to the
contents of the formal parameter will reflect on the original value of the variable.

P34. A program to illustrate the function using call by Address.

Call by reference: In this method instead of passing arguments by value, a


reference to the original variable in the calling function is passed. Hence the
reference parameter refers the same memory location by another name. Here the
reference parameter acts as alias (different name) to the actual parameter.
If any changes made to the contents of the variables in the called function
(formal parameter) also changes the original value of the variable.

P35. A program to illustrate the function using call by reference mechanism.

Difference between Call by Value and Call by Reference

Call by Value Call by Reference


Values are passed as arguments References are passed as arguments
The function operates on the actual
The functions operate on the copy of the
arguments themselves. As a result, the
actual arguments. As a result, no
values of the actual arguments are
changes in actual arguments.
altered.

The function can not return more than It simulates a function that can return
one value more then one value.
Constants can be passed as arguments Constants can not be passed as
arguments.

Example : For the function with the Example: For the function with the
following prototype following prototype

int add(int, int); int add(int&, int&);

k=add(10,4); k = add(10,4);

is a valid function call. Is a invalid function call

Mahesha. S SSC, Tumkur Cell : 9886044689


C++ Programming 44 Functions

Function overloading (Function polymorphism)

Definition: Several functions have same name but differ in input parameter list are
called overloaded functions. OR
“Two or more functions are said to be overloaded if they have same name but
have different argument list”. Argument list refers to the number of arguments &
data type of the arguments.
Using the concept of function overloading, we can design a family of functions
with one function name but with different argument list. The function would perform
different operations depending on the argument list in the function call. The correct
function to be invoked is determined by checking the number and type of the
arguments but not on the function type.

Declarations:
e.g. int add(int a, int b); //prototype-1
float add (float a, float b); //prototype-2
long int add (long int a, long int b); //prototype-3
Function call:
cout<<add (5, 9);
cout<<add(12.3,22.8);
cout<<add(45L,9L);

A function call first matches the prototype having the same number and type
of arguments and then calls the appropriate function for execution. A best match
must be unique. The function selection involves the following steps:

1. The compiler first tries to find an exact match in which the types of actual
arguments are the same and use that function.
2. If an exact match is not found, the compiler uses the integral promotions to
the actual arguments, such as,
char to int
float to double
to find a match.
3. When either of them fails, the compiler tries to use the built-in conversions
(the implicit assignment conversions) to the actual arguments and then uses
the function whose match is unique. If the conversion is possible to have
multiple matches, then the compiler will generate an error message.
Suppose we use the following two functions:
long square(long n)
double square(double x)
A function call such as
square(10);
will cause an error because int argument can be converted to either long or
double, thereby creating an ambiguous situation as to which version of
square() should be used.

Mahesha. S SSC, Tumkur Cell : 9886044689


C++ Programming 45 Functions

4. If all of the steps fail, then the compiler will try the user-defined conversions in
combination with integral promotions and built-in conversions to find a unique
match. User-defined conversions are often used in handling class objects.

P35. WAP to find the factorial of a number by function overloading.


Function with default arguments: C++ language provides the programmer a
short hand way to use overloaded functions called default arguments method. In this
method programmer supplies default values for the inputs. If the function is called
and the values are not passed to it, the function uses the default values supplied in
the declaration / function prototype.
e.g.
long factorial (int n=5);
cout<<factorial();
Here the function factorial will operate on the default value n=5.
Cout<<factorial(3);
Here the function factorial will operate on the value n=3 instead of the
default value n=5.

Advantages:
 Default arguments are used to combine similar functions or group of functions into a
single function.
 The default arguments to add new parameters to the existing functions.
 The Default arguments are given only in the function prototype.

P36. WAP to find the factorial of a given integer by default arguments.

Inline Functions: The concept of functions was invented primarily to modularize


programs to save memory space. Once we define a function, it can be invoked
anywhere in a program and any number of times. That is the beauty of the functions.
Each invocation of a function results in a number of operations to be carried out by
the processor. They are: jumping to the function, saving registers (memory),
pushing arguments to the stack and returning back to calling function. One solution
for this problem is to use macros. The drawback of macros is that, they are not
functions and also error checking does not occur during compilation.

To solve such problems C++ provides a new feature called inline function. It
reduces the runtime function overhead.
“An inline function is a function that is expanded in line when it is invoked i.e. the
compiler replaces the function call with the corresponding code itself”.
Syntax: inline return-type function-name (arg-list)
{
Function-body
}

P37. WAP to find the square of a given integer using inline function.

P38. WAP to check whether the given number is a prime or not using inline functions.

Mahesha. S SSC, Tumkur Cell : 9886044689


C++ Programming 46 Functions

Note: i) The qualifier inline is used only if the function body is too small
ii) The inline function must be defined before it is called.
iii) The inline is not a command; it is a request made to the complier. Hence there is no
guarantee that the code gets inserted when the call is made.
iv) If the function is too long, the compiler may ignore the request.

STORAGE CLASSES: The storage class is a class of variables that define the scope
and lifetime of variable in a program.

Scope of a variable is the area of its existence. Lifetime of a variable is the


duration of its availability in a program. Depending on where a variable is allocated
required storage, the area of its existence in a program (scope), and its lifetime is
defined in storage classes.
The variable in C++ can have one of the 4 storage classes.
1. Automatic storage classes.
2. External storage classes.
3. Static storage classes.
4. Register storage classes.
1. Automatic storage classes: This applies only with in a function. The variable is
created when the function is called and automatically destroyed when the function
exits. Hence automatic variables are also called internal variables or local variables.
Syntax: auto int x , y ;

Automatic variables are characterized by the following properties:

1. They get created on entry into their function.


2. They get automatically destroyed on the exit of their function.
3. They are visible within the function only.
4. Their lifetime is the duration of the function only.
5. If not initialized, they will have garbage values.
6. If initialized, they would be reinitialized on each entry into the function.
7. They can not be declared outside of functions.
P39. WAP to illustrate the working of automatic variable

#include<iostream.h>
#include<conio.h>
void main()
{
auto int a = 100; Output:
function1();
cout<< a <<endl; 1
} 10
100
function1()
{
auto int a = 10;
function2();
cout<< a <<endl;
}

Mahesha. S SSC, Tumkur Cell : 9886044689


C++ Programming 47 Functions

function2()
{
auto int a=1;
cout<<a<<endl;
}

2. External storage classes: It is just like a global declaration of variable.


Variables that are alive and active throughout the entire program are called external
variables.
Syntax: extern int n;

P40. WAP to illustrate the working of extrnal variable

#include<iostream.h>
#include<conio.h>
void main()
{
extern int n=100;
output ();
} Output
n=100
int n
output ()
{
cout<<“n=”<<n;
getch();
}

3. Static storage classes: (static means constant)


The value of static variables persists until the end of the program. As a result
of a function exits and re-entered again the value of the variable is continued (its
does not initialized again). These variables are initialized only once at the time of
compilation and never initialized again and again while enter into the function. By
default variable initializes by zero.

Syntax: static int a, b;

Staticvariables are characterized by the following properties:


1. They get created on the entry into their enclosing function.
2. They are not destroyed on the function’s exit.
3. They are initialized to 0 by default.
4. They are not reinitialized on the re-entry into the function. The previous values
persist.
5. They are visible within the function body.
6. Their lifetime is the duration of the entire program’s duration.
7. They can be declared either within or outside of function.

Mahesha. S SSC, Tumkur Cell : 9886044689


C++ Programming 48 Functions

P41. WAP to illustrate the property of static variable.


void main()
{
int n;
for(n=1;n<=3;n++)
function() Output:
}

function() P=10
{ P=20
static int p=0; P=30
cout<<“p=”<< p+10;
getch();
}

Note: In this program if p is declared as auto variable, the output would be

P=10
P=10
P=10

4. Register storage class: At the time of execution the value of the variable is
stored in CPU memory. If the value of the variable is repeatedly required as in
looping statement, a lot of computer time is wasted at the time of processing for that
we are storing a value in CPU register. This register is much faster than memory.
Syntax: register int a, b, c;

P42. WAP to illustrate the property of register variable.

void main()
{
register int n;
for(n=1;n<=3000;n++)
cout<<endl<<” n = “ << n;
}

Review Questions

One mark Questions:


1. What is the need for the functions?
2. Write the syntax of function prototype.
3. What is the function header?
4. What is meant by default argument?
5. Define function prototype.
6. What do you mean by lifetime of the variable?
7. Define function overloading.
8. How many values a function return?
9. What does the return statement play?

Mahesha. S SSC, Tumkur Cell : 9886044689


C++ Programming 49 Functions

Three marks Questions:


1. Define an inline function. How does an inline function differ from pre-processor
macro?
2. Write the difference between call by value and call by reference.
3. Explain static storage class.
4. Define actual and formal arguments with an example.
Seven marks Questions:
1. a. What is the use of reference variable? Explain with programming example.
b. Write a program to find the factorial of a number by using function overloading.
2. a. What is function overloading? What is the advantage of overloaded functions?
b. Write a program to check whether a number is prime using function overloading.
3. a. What is mean by storage classes? What are the differences between automatic
and static variable?
b. Write a program to find the factorial of a number by default argument method.

Mahesha. S SSC, Tumkur Cell : 9886044689

You might also like