0% found this document useful (0 votes)
3 views14 pages

C++ Function Basics and Usage

The document provides an overview of functions in C++, including their definition, syntax, advantages, and classification into library and user-defined functions. It covers various aspects such as function prototypes, calls, definitions, argument passing methods (call by value, address, and reference), default and const arguments, inline functions, function overloading, and recursion. Additionally, it outlines the principles and precautions of function overloading and the rules for recursive functions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

C++ Function Basics and Usage

The document provides an overview of functions in C++, including their definition, syntax, advantages, and classification into library and user-defined functions. It covers various aspects such as function prototypes, calls, definitions, argument passing methods (call by value, address, and reference), default and const arguments, inline functions, function overloading, and recursion. Additionally, it outlines the principles and precautions of function overloading and the rules for recursive functions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 1 Functions

Function: 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.
The most common syntax to define a function is:
return_type function_name ( parameter1, parameter2, ...)
{
statements
}
Where:
- return_type is the type of the value returned by the function.
- function_name is the identifier by which the function can be called.
- parameters (as many as needed): Each parameter consists of a type followed by an
identifier, with each parameter being separated from the next by a comma
- statements is the function's body. It is a block of statements surrounded by braces { } that
specify what the function actually does.

Advantages:

Reusability: A function once written can be invoked again and again, thus helping us to
reuse the code and removing data redundancy.
Modularity: Functions can help us in breaking a large, hard to manage problem into
smaller manageable sub-problems.
Reduced Program Size: Functions can reduce the size of the program by removing data
redundancy.
Easy Debugging: Using functions, debugging of a program becomes very easy, as it is
easier to locate and rectify the bug in the program if functions are used.
Easy Updating: If we need to update some code in the program, then it is much more
easier in case we have used functions, as the changes need to be made in one place only
(in function).

1
Unit 1 Functions

C++ functions are classified in two categories. They are


Library functions and
User-defined functions.

The library functions can be used in any program by including respective header files. The
header files must be included using #include pre-processor directive. For example, a mathematical
function uses math.h header file. The programmer can also define and use his/her own functions
for performing some specific tasks. Such functions are called user-defined functions.

Parts of A Function: Parts of a function are as follows.

1. Function prototype declaration


2. Function call
3. Definition of a function
4. Actual and formal arguments
5. Return statement

2
Unit 1 Functions

1. Function prototype Declaration: A function prototype declaration consists of function’s


return type, name, and arguments list. The statements given below are the examples of
function prototypes.
void show (void); float
sum (float, int); float
sum (float x, int y);

2. Function Call: A function must be called by its name followed by argument, or without
argument, list enclosed in parenthesis and terminated by semicolon.

Syntax of function call is as follows:

function-name(with/without argument list);

In the above statement, function-name is the name of the function, arguments are within
the bracket and arguments are separated by comma. If arguments are absent one can write
void within the bracket.

3. Function Definition: The first line is called function definition and function body follows
it. The function definition and function prototype should match with each other. The
function body is enclosed within curly braces. The function can be defined anywhere. If
the function is defined before its caller, then its prototype declaration is optional.

Syntax of function call is as follows:

return_data_type function-name(argument/parameter list);


{
variable declarations
function statements
}

4. Actual and Formal Argument: The arguments declared in caller function and given in
the function call are called actual arguments. The arguments declared in the function
definition are known as formal arguments.
3
Unit 1 Functions

5. The return Statement: The return statement is used to return value to the caller function.
The return statement returns only one value at a time. When a return statement is
encountered, complier transfers the control of the program to caller function. The syntax of
return statement is as follows:

return (variable name); or

return variable name;

Passing Arguments:

The main objective of passing argument to function is message passing. The message passing
is also known as communication between two functions, that is between caller and called
functions. There are three methods:

1. Call by value (pass by value)


2. Call by address (pass by address)
3. Call by reference (pass by reference)

Call by Value: In this type, values of actual arguments are passed to the formal arguments and
operation is done on the formal arguments. Any change in the formal arguments does not effect to
the actual arguments because formal arguments are photocopy of actual arguments. Changes made
in the formal arguments are local to the block of called function. Once control returns back to the
calling function, the changes made will vanish.
The following example illustrates the use of call by value.
#include<iostream.h>

void swap (int, int);

int main()
{
int x,y;
cout<<“\n Enter Values of X & Y:”;
cin>>x>>y;
cout<<“\n\n In function main() before swap()”;
cout<<“\n Values X=”<<x <<“ and Y= ”<<y;

4
Unit 1 Functions

swap(x,y);
cout<<“\n\n In function main() after swap() ”;
cout<<“\n Values X=”<<x <<“ and Y= ”<<y;
return 0;
}
void swap(int a, int b)
{
int k;
k=a;
a=b;
b=k;
cout<<“\n In function swap() ”;
cout<<“\n Values X=”<<a <<“ and Y= ”<<b;
}

Output:

Enter Values of X & Y :5 4


In function main() before swap() Values X=5 and Y= 4
In function swap() Values X=4 and Y= 5
In function main() after swap() Values X=5 and Y= 4

Call by Address: In this type, instead of passing values, addresses of actual parameters are
passed to the function by using pointers. Function operates on addresses rather than values. Here
the formal arguments are pointers to the actual arguments. Because of this, when the values of
formal arguments are changed, the values of actual parameters also change. Hence changes made
in the argument are permanent. The following example illustrates passing the arguments to the
function using call by address method.

#include<iostream.h>
void swap (int *, int *);
int main()
{
int x,y;
cout<<“\n Enter Values of X & Y:”;
cin>>x>>y;
swap(&x,&y);

5
Unit 1 Functions

cout<<“\n In main() Values X=”<<x <<“ and Y=”<<y;


return 0;
}
void swap(int *a, int *b)
{
int *k;
*k=*a;
*a=*b;
*b=*k;
cout<<“\n In swap() Values X=”<<*a <<“ and Y=”<<*b;
}

OUTPUT

Enter Values of X & Y :5 4


In swap()Values X=4 and Y=5
In main()Values X=4 and Y=5

Call by Reference: C passes arguments by value and address. In C++ it is possible to pass
arguments by reference. C++ reference types, declared with ‘&’ operator, they declare aliases
for objects variables and allow the programmer to pass arguments by reference to functions. The
reference decelerator (&) can be used to declare references outside functions.

For Ex.

int k = 0;
int &kk = k; // kk is an alias for k
kk = 2; // same effect as k = 2

Example:

#include<iostream.h>
void swap (int &, int &);

int main()
{
int x,y;

6
Unit 1 Functions

cout<<“\n Enter Values of X & Y:”;


cin>>x>>y;
swap(x,y);
cout<<“\n In main()Values X=”<<x <<“ and Y=”<<y;
return 0;
}
void swap(int &a, int &b)
{
int k;
k=a;
a=b;
b=k;
cout<<“\n In swap()Values X=”<<a <<“ and Y=”<<b;
}

Output:

Enter Values of X & Y :5 4


In swap()Values X=4 and Y=5
In main()Values X=4 and Y=5

Default Arguments: A default argument is a value provided in function declaration that is


automatically assigned by the compiler if the caller of the function does not provide a value for
the argument.

Ex:

#include <iostream.h>
int sum(int a, int b=10, int c=20, int d=30)
{
return a+b+c+d;
}
int main() {
int a=2,b=3,c=4,d=5;
cout<<"Sum:"<<sum(a,b,c,d)<<endl;
cout<<"Sum:"<<sum(a,b,c)<<endl;
cout<<"Sum:"<<sum(a,b)<<endl;
cout<<"Sum:"<<sum(a)<<endl;
return 0;
}

7
Unit 1 Functions

Output:
Sum:14
Sum:39
Sum:55
Sum:62

Const Arguments: The constant variable can be declared using const keyword. The const
keyword makes variable value stable.

Ex. The following program generates an error

#include <iostream.h>
int increment(const int a);
int main() {
int a=2;
cout<<"Incremented val:"<<increment(a);
return 0;
}
int increment( const int a)
{
return ++a;

Output:

error: increment of read-only parameter 'a'

Inline Functions: When a function is declared as inline, the compiler copies the code of the
function in the calling function. i.e., function body is inserted in place of function call during
compilation.

Syntax:
inline function_name(with or without arguments)
{
statement 1;
statement 2;
}

8
Unit 1 Functions

Following are few situations where inline functions may not work:

1. The function should not be recursive.


2. Function should not contain static variables.
3. Function containing control structure statements such as switch, if, for loop, etc.
4. The function main() cannot be used as inline.
The inline functions are similar to macros of C. The main limitation of macros is that they
are not functions, and errors are not checked at the time of compilation. The function offers
better type testing and does not contain limitations as present in macros. Consider the following
example:

#include <iostream.h>

inline int Max(int x, int y)


{
return (x > y)? x : y;
}
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;

}
Output:
Max (20,10): 20
Max (0,200): 200
Max (100,1010):1010

Function Overloading

It is possible in C++ to use the same function name for number of times and for different
intentions. Defining multiple functions with same name is known as function overloading or
function polymorphism. Polymorphism means one function having many forms. The overloaded
function must be different in their argument list and with different data types. The following are
examples of overloaded functions. All the functions defined should be equivalent to their
prototypes.

int test() { } int


test(int a){ }
int test(double a){ }
int test(int a, double b){ }

9
Unit 1 Functions

Example:

#include <iostream.h>

void test(int); void


test(float); void
test(int, float);

int main() { int


a = 5; float b
= 5.5;

test(a);
test(b);
test(a, b);

return 0;
}

void test(int var) {


cout<<"Integer number: "<<var<<endl;
}
void test(float var){
cout<<"Float number: "<<var<<endl;
}
void test(int var1, float var2) {
cout<<"Integer number: "<<var1;
cout<<" and float number:"<<var2;
}

Output:
Integer number: 5
Float number: 5.5
Integer number: 5 and float number:5.5

Principles of Function Overloading:

1. If two functions have the similar type and number of arguments (data type), the
function cannot be overloaded. The return type may be similar or void, but argument
data type or number of arguments must be different. For example,
a) sum(int,int,int);

10
Unit 1 Functions

sum(int,int);

Here, the above function can be overloaded. Though the data type of arguments in
both the functions are similar, number of arguments are different.

b) sum(int,int,int);

sum(float,float,float);

In the above example, number of arguments in both the functions are same, but
data types are different. Hence, the above function can be overloaded.

2. Passing constant values directly instead of variables also results in ambiguity.


3. The compiler attempts to find an accurate function definition that matches in types and
number of arguments and invokes that function. The arguments passed are checked
with all declared function. If matching function is found then that function gets
executed.
4. If there are no accurate match found, compiler makes the implicit conversion of actual
argument. For example, char is converted to int and float is converted to
double.
5. If internal conversion fails, user-defined conversion is carried out with implicit
conversion and integral promotion.

Precautions with Function Overloading

1. Only those functions that basically do the same task, on different sets of data, should
be overloaded. The overloading of function with identical name but for different
purposes should be avoided.
2. In function overloading, more than one function has to be actually defined and each of
these occupy memory.
3. Instead of function overloading, using default arguments may make more sense and
fewer overheads.
4. Declare function prototypes before main() and pass variables instead of passing
constant directly. This will avoid ambiguity that frequently occurs while overloading
functions.

11
Unit 1 Functions

Recursion:

In many programming languages including C++, it is possible to call a function from a


same function. This function is known as recursive function and this programming technique is
known as recursion.

In recursion a function calls itself and the control goes to the same function and it
executes repeatedly until some condition is satisfied. In this type of recursive calls a function
starts with a new value every time.

Rules for Recursive Function

1. In recursion, it is essential to call a function by itself; otherwise recursion would not take
place.
2. Only the user-defined function can be involved in the recursion. Library function cannot
involve in recursion because their source code cannot be viewed.
3. A recursive function can be invoked by itself or by other function. It saves return address
with the intention to return at proper location when return to a calling statement is made.
The last-in-first-out nature of recursion indicates that stack data structure can be used to
implement it.
4. To stop the recursive function, it is necessary to base the recursion on test condition, and
proper terminating statement such as exit() or return() must be written using the if()
statement.

Example:

#include<iostream.h>

int main()
{
unsigned long int fact(int);
dint f,x;
cout<<“\nEnter a Number:”;
cin>>x;
f=fact(x);
cout<<“\nFactorial of ” <<x <<“ is ”<<f;
return 0;
}
unsigned long int fact(int a)
{
unsigned long factorial;
if(a==1)

12
Unit 1 Functions

return 1;
else
factorial=a*fact(a-1);
return factorial;
}

Output:
Enter a Number:6
Factorial of 6 is 720

Library Functions:

ceil, ceill and floor, floorl: The functions ceil and ceill round up the given float number,
whereas the functions floor and floorl round down the float number. They are defined in math.h
header file. Their declarations are as given below.

double ceil(double n);


double floor(double n);
dlng double ceill(long double (n));
long double floorl(long double (n));

modf and modfI: The function modf breaks double into integer and fraction elements, and
the function modfl breaks long double into integer and fraction elements. These functions
return the fractional elements of a given number. They are declared as given below.

double modf(double n, double *ip);


long double modfl(long double (n), long double *(ip));

Ex.

int main() Output:


{
double f, i; The Complete Number :
double num = 211.57; 211.57
f = modf(num, &i);
cout<<“\n The Complete Number: The Integer elements : 211
”<<num;
cout<<“\n The Integer elements: ”<<i; Fractional Elements : 0.57
cout<<“\n Fractional Elements: ”<<f;
return 0;
}

13
Unit 1 Functions

abs, fabs, and labs: The function abs() returns the absolute value of an integer. The fabs()
returns the absolute value of a floating-point number, and labs() returns the absolute value of
a long number.

int abs(int n);


double fabs(double n);
long int labs(long int n);

14

You might also like