0% found this document useful (0 votes)
17 views25 pages

C++ - FUNCTION

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
17 views25 pages

C++ - FUNCTION

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 25

Functions: Introduction, Prototype, Passing Data by Value, Reference Variables,

Using Reference Variables as Parameters, Inline Functions, Default Arguments,


Overloading Functions, Passing Arrays to Functions.

✔​ Function:

▪​ A function is a group of statement that together perform a


task, the program code can be divided into separate function.
Each function performs a specific task.

✔​ Introduction:

▪​ Every C++ program must have a main() function to


indicate where the program has to begin its execution.
▪​ The program may become too large and complex and as a
result the task of debugging, testing, and maintaining
becomes difficult.
▪​ If a program is divided into functional parts, then
each part may be independently coded and later
combined into a single unit.
▪​ This subprogram called ‘function’ are much easier to understand, debug, and
test.
▪​ There are times when certain type of operations or calculation is repeated at
many points throughout a program.

​ Element of function:

​ In order to make use of user-defined function, we need to establish the


element that are related to function.

1.​Function definition
2.​Function call
3.​Function declaration

​ Definition of function:

​ A function definition, also known as function implementation.

1.​ Function name


2.​ Function type
3.​ List of parameter
4.​ Local variable declaration.
5.​ Function statement.
6.​ A return statement.

​ A general format of a function definition to implementation these two parts.


Function_type function_name (parameter list)
{
Local variable declarartion;
Executable statement 1;
Executable statement 2;
……………………………
Return statement;
}
​ Function header – it consists of 3 parts: the function type(also known as return
type, the function name and the formal parameter list). Note that semicolon is
not used at the end of the function header

​ Name and Type – function type specifies the type of value (like float or double).
If the return type is not explicitly specified, C will assume that it is an integer
type. The function name in any valid C identifier and therefore must follow the
same rules of formation as other variable names in C. The name should be
approximate to the task performed by the function.

​ Formal parameter list

​ The parameter list declares the variable that will receive the data sent by the
calling program. They serve as input data to the function to carry out specified
task.
​ These parameters can also be used to send values to the calling programs.
The parameters are also known as arguments.
​ The parameters list contains declaration of variables separated by commas
and surrounded by parentheses.

Examples:
float quadratic (int a, int b, int c) {….}
Double power (double x, int n) {….}
float mul (float x, float y) {….}
int sum (int a, int b) {….}

​ There is no semicolon after the closing parenthesis, the declaration of


parameter variables cannot be combined. i.e., int sum(int a, b) is illegal.
​ A function need not need not always receive values from the calling program.
The parameter list is empty, we use the keyword void between the
parentheses.

Void printline(void)
{
…………….
}

▪​ This function neither receives any input values nor returns back any value,many
compliers accept are empty set of parentheses, without specifying anything as in

Void printline()
Function Body

▪​ The function body contains the declarations and statement necessary for
performing the required task.
▪​ The body enclosed in braces, contains 3 parts, in the order given below:
1.​ Local declarations that specify the variables needed by the function.
2.​ Function statements that perform the task of the function.
3.​ A return statement that returns the value evaluated by the function.

​ Return values and their types

​ A function may or may not send back any value to the calling function. If it
does, it is done through the return statement.
​ The return statement can take one of the following forms:

return;​ or​ return(expression);

the ‘plain’ return does not return not value; it acts much as the closing brace
of the function.

​ Prototype

​ A function prototype is also known as function declaration. Function prototype


consists of 4 parts
1.​ Function type(return type)
2.​ Function name
3.​ Parameter list
4.​ Terminating semicolon

​ They are coded in following format:

Function-type function-name (parameter list);

​ A prototype declaration may be placed in 2 places in a program.


1.​ Above all the functions(including main)
2.​ Inside a function definition.
​ When we place the declaration above all the functions (in the global
declaration section), the prototype is referred to as a global prototype.
​ When place it in a function (in the local declaration section), the prototype is
called a local prototype.
​ The function defined by the user is also known as User-defined functions.

​ Need for functions:

1.​ It provides modularity to your program’s structure.


2.​ It makes your code reusable. You just have to call the function by its name to
use it, whenever required.
3.​ In case of large programs with thousands of code lines, debugging and editing
becomes easier if you use functions.
4.​ It makes the program more readable and easy to understand.

​ Elements of function definition

​ The general syntax of function definition is,

returntype functionName(type 1 parameter1, type 2 parameter2,….)


{
//function body goes here
}

​ Function definition consists of 4 parts.


1.​ Return type
2.​ function name
3.​ parameter list
4.​ function body

1.​ return type – when a function is declared to perform some sort of calculation or
any operation and is expected to provide with some result at the end.
NOTE: in case your function doesn’t return any value, the return type would be
void.
2.​ Function name – function name is an identifier and it specifies the name of the
function.
3.​ Parameter list – the parameter list declares the type and number of arguments
that the function expects when it is called.
4.​ Function body – the function body contains the declaration and the
statement(algorithm) necessary for performing the required task.
The body is enclosed within curly braces {….} and consists of 3 parts.
1.​ Local variable declaration(if required).
2.​ Function statement to perform the task inside the function.
3.​ A return statement to return the result evaluated by the function(if return
type is void, then no return statement is required).

​ Function calls
When a function is called, control of the program gets transferred to the function.

functionName(argument 1,argument 2,….);

Passing arguments to a function:

A B a&b a|b a^b ~a

0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0
It is possible to have a function with parameters but no return type. It is not
necessary, that if a function accepts parameter(s), it must return a result too.
​ While declaration the function, we have declared 2 parameters a and b of
type int. therefore, while calling that function, we need to pass 2 arguments,
else we will get complication error.
​ And the two arguments passed should be received in the function definition,
which means that the function header in the function definition should have
the 2 parameters to hold the argument values.
​ These received arguments are also known as formal parameters. The name
of the variables while declaring, calling and defining a function can be
different.

PROGRAM
#include<iostream>
Using namespace std;
#include<conio.h>
int multiply(int a, int b); //function declaration
int main()
{
int i, j, result;
cout<<” Enter 2 numbers you want to multiply: “;
cin>>i>>j;
result = multiply(i, j); //function call
cout<<”The result of multiplication is: ”<<result;
getch();
return 0;
}
int multiply(int a, int b)
{
return(a*b); //function definition, this can be done in one line
}
Output: Enter 2 numbers you want to multiply: 5 6
The result of multiplication is: 30

​ Passing Data by Value

​ In pass by value parameter passing method, values of actual parameters are


copied to function’s formal parameters and the 2 types of parameters are
stored in different memory locations.
​ So any changes made inside functions are not reflected in actual parameters
of caller.

Pass by value
PROGRAM
#include <iostream>
using namespace std;

// function declaration
void swap(int x, int y);

int main () {
// local variable declaration:
int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;


cout << "Before swap, value of b :" << b << endl;

// calling a function to swap the values.


swap(a, b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;
return 0;
}

// function definition to swap the values.


void swap(int x, int y) {
int temp;

temp = x; /* save the value of x */


x = y;​ /* put y into x */
y = temp; /* put x into y */
return;
}
OUTPUT:

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

​ In main(), two integer a and b are defined. And those integers are passed to a
function swap() by value.
Void swap(int x, int y);

​ The values of actual parameters (variable a and b) are copied to swap()


function’s formal parameters (variable x and y), the two types of parameters
are stored in different memory locations.
​ Swapping takes place in the address of the variable x and y. so the changes
made inside swap() function are not reflected in main() function.

​ Passing Data by pointer

​ The call by pointer method of passing arguments to a function copies the


address of an argument into the formal parameter (pointers).
​ ​To pass the value by pointer, actual parameters are passed to the function as

address and formal parameters are declared as type pointer

Pass by pointer
PROGRAM

#include <iostream>
using namespace std;
#include<conio.h>
// function declaration
void swap(int *x, int *y);

int main () {
// local variable declaration:
int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;


cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values.


*​&a indicates pointer to a ie. address of variable a and
*​&b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;

return 0;
}

// function definition to swap the values.


void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y */

return;
}

OUTPUT
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

​ Swap (&a, &b); //&a is address of a &b is address of b

​ The *X and *Y gives the value stored at address X and Y respectively.

​ Since pointer variable x contains the address of variable a, anything done to


*x changes the value of variable a in main () function as well. Similarly,
variable b will have same value as *y.
​ Using reference variables as parameters

​ Reference – another name for an already existing variable.

​ In pass by reference method the actual value of the argument is not passed.

Pass by reference

PROGRAM

#include <iostream>
using namespace std;
#include<conio.h>

// function declaration
void swap(int &x, int &y);

int main () {
// local variable declaration:
int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;


cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values using variable reference.*/


swap(a, b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;

return 0;
}
// function definition to swap the values.
void swap(int &x, int &y) {
int temp;
temp = x; /* save the value at address x */
x = y;​ /* put y into x */
y = temp; /* put x into y */

return;
}

OUTPUT

Before swap, value of a:100


Before swap, value of b:200
After swap, value of a:200
After swap, value of b:100

In main(), 2 integer variables a and b those integers are passed to a function


swap() by reference.

​ Difference between Call by value and Call by reference

Call by Value Call by Reference

The actual arguments can be The actual arguments can only be


variable or constant. variable.
The values of actual argument are The reference of actual argument are
sent to formal argument which are sent to formal argument which are
normal variables. pointer variables.

Any changes made by formal


Any changes made by formal arguments
arguments will not reflect to actual
will reflect to actual arguments
arguments.

​ Type of user-defined Functions in C++

​ There can be 4 different types of user-defined functions, they are:

1.​ Function with no arguments and no return value


2.​ Function with no arguments and a return value
3.​ Function with arguments and no return value
4.​ Function with arguments and a return value
1.​ Function with no arguments and no return value

▪​ Such functions can either be used to display information or they are


completely dependent on user inputs.
▪​ There is no data transfer between the calling function and the called function.
▪​ The dotted lines that there is only a transfer of control but not data
▪​ Below is an example of a function, which takes 2 numbers as input from user,
and display which is the greater number.

#include<stdio.h>
Using namespace std;
#include<conio.h>
void greatNum();​ // function declaration
int main()
{
greatNum();​ // function call
return 0;
}
void greatNum()​ // function definition
{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {
printf("The greater number is: %d", i);
}
else {
printf("The greater number is: %d", j);
}
}

OUTPUT:
Enter 2 number that you want to compare:25 45
The greater number is:45
2.​ Function with no arguments and a return value

We have modified the above example to make the function greatNum() return
the number which is greater amongst the 2 input numbers.

#include<stdio.h>
Using namespace std;
#include<conio.h>
int greatNum();​ // function declaration
int main()
{
int result;
result = greatNum();​ // function call
printf("The greater number is: %d", result);
return 0;
}
int greatNum()​ // function definition
{
int i, j, greaterNum;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {
greaterNum = i;
}
else {
greaterNum = j;
}
// returning the result
return greaterNum;
}

3.​ Function with arguments and no return value

▪​ We are using the same function as example again and again; to


demonstrate that to solve a problem there can be many different ways.
▪​ This time, we have modified the above example to make the
function greatNum() take two int values as arguments, but it will not be
returning anything.
PROGRAM
#include<stdio.h>
Using namespace std;
#include<conio.h>
void greatNum(int a, int b);​ // function declaration
int main()
{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
greatNum(i, j);​ // function
call return 0;
}
void greatNum(int x, int y)​ // function definition
{
if(x > y)
{
printf("The greater number is: %d", x);
}
else {
printf("The greater number is: %d", y);
}
}

4.​ Function with arguments and a return value

▪​ This is the best type, as this makes the function completely independent of
inputs and outputs, and only the logic is defined inside the function body.

#include<stdio.h>
Using namespace std;
#include<conio.h>
int greatNum(int a, int b);​ // function declaration
int main()
{
int i, j, result;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
result = greatNum(i, j); // function call
printf("The greater number is: %d", result);
return 0;
}
int greatNum(int x, int y)​ // function definition
{
if(x > y) {
return x;
}
else {
return y;
}
}

​ Inline functions

​ Inline function is a function that is expanded in line when it is called. When


the inline function is called whole code of the inline function gets inserted
or substituted at the point of inline function call.

​ Why inline functions?

​ When a program executes the function call instructions, the CPU stores the
memory address of the instruction following the function call, copies the
arguments of the function on the stack and finally transfers control to the
specified function.
​ In lining is only a request to the complier, not a command.

​ Complier may not perform inlining in such circumstances like:

1.​ If a function contains a loop (for, while, do-while)


2.​ If a function contains static variables.
3.​ If a function is recursive.
4.​ If a function return type is other than void, and the return statement
doesn’t exist in function body.
5.​ If a function contains switch or goto statement.

​ Advantage and disadvantages of inline function

●​ Advantage:

1.​ Function call overhead doesn’t occur.


2.​ It also saves the overhead of push/pop variables the stack when function
is called.
3.​ It also saves overhead of a return call from a function.

●​ Disadvantage:

1.​ The added variables from the inline function consume additional registers.
2.​ If too many inline functions are used then the size of the binary
executable file will be larger, because of the duplication of same code.
3.​ Too much inlining can also reduce our instruction cache hit rate, thus
reducing the speed of instruction fetch from that of cache memory to that
of primary memory.

PROGRAM:
#include<stdio.h>
Using namespace std;
#include<conio.h>
inline int cube(int s)
{

Return s*s*s;
}
int main()
{
Cout<<”the cube of 3 is: “<<cube(3)<<”\n”;
Getch();
Return 0;
}

OUTPUT:
The cube of 3 is: 27

​ Passing Arrays to Functions

​ It is also possible to pass the values of an array to a function.

​ Passing One-Dimensional Array to Function


​ To pass a one-dimensional an array to a called function, it is sufficient to list
the name of the array, without any subscripts, and the size of the array as
arguments.
​ For example, the call

Largest (a, n)

▪​ The function largest is defined to take 2 arguments, the array name and the
size of the array to specify the number of elements in the array.
▪​ The declaration of the formal argument array is made as follows:

Float array[];

▪​ The pair of brackets informs the complier that the arguments array is an array
of numbers. It is not necessary to specify the size of the array here.

PROGRAM
#include<iostream>
Using namespace std;
#include<conio.h>
//function declaration
int largest (int a[], int n);
int main()
{
int arrValues[5] = {3,-4,65,24,48};
int results = largest(arrValues, 5);
cout<<”Largest is “<<result;
getch();
return 0;
}
int largest(int a[], int n)
{
int i,max;
max = a[0];
for(i=1;i<n;i++)
if(max<a[i])
max=a[i];
return(max);
}
OUTPUT:
Largest is 65

▪​ The value of actual parameters (arrValues and 5) are copied to


largest()function’s formal parameter (a and n).
▪​ The function largest() value in the array and returns it to main(). The array
name, we are, in fact, passing the address of the array to the called function.
▪​ ​The array in the called function now refers to the same array stored in the
memory.
▪​ Therefore, any changes in the array in the called function will be reflected in
the calling function. Passing address of parameters to the functions is referred
to as pass by address.

​ Passing Two-Dimensional Array to Functions

​ We can also pass multidimensional arrays to functions.

​ The approach is similar to the one we did with one-dimensional arrays. The
rules are simple.
1.​ The function must be called by passing only the array name.
2.​ In the function definition, we must indicate that the array has two
dimensions by including two sets of brackets.
3.​ The size of the second dimension must be specified.
4.​ The prototype declaration should be similar to the function header.

▪​ The function given below calculates the sum of the values in a two-
dimensional matrix.

PROGRAM
#include<iostream>
Using namespace std;
#include<conio.h>
//function declaration
double sum(int x[2][2], int r,int c);
int main()
{
int arrValues[2][2]={
{1, 2},
{3, 4}
};
int result = sum(arrValues, 2,2);
cout<<”sum is”<<result;
getch();
return 0;
}
double sum(int x[2][2], int r,int c)
{
int i,j;
double sum = 0.0;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
sum += x[i][j];
return sum;
}
OUTPUT:
Sum is 10

You might also like