×
>
<

Aptitude

C++ Functions

Functions

Instead of writing the repeated code again and again in the program, It can be put together under a block with a name and reuse later.
Definition: Function is a self-defined block which performs a predefined task
A function can be reused any number of times and anywhere in the program

Types of Functions

1.Predefined functions

  • These functions are been already defined by the designer and placed in the library 
  • We can make use of these library functions to get the pre-defined output instead of writing our own code to get those outputs.
  • ex: pow() in math.h ,printf() in stdio.h

2. User defined functions

  • These are defined and customized by the user per the requirement
  • ex: add()

Function Components

To write the programs on function on any language we should understand the following 8 components

1.Function declaration(prototype)

  • Function declaration tells the compiler the return type of the functions, number of arguments, function  return type of the arguments and order of arguments
  • A function declaration  can be inside or outside the main() but the before  function call;

Syntax:

  
return_type func_name(arg1,arg2..argn);
  

Example:

  
int sum(int,int);
  

The above function takes 2 inputs of type int and returns the output of type int

2.Function definition

  • The set of statements which defines the task of the function
  • The return type must be mentioned in function definition which is the same given in function prototype

Example :

  
int sum(int x,int y)// function defination
{
return x+y; 
}
  
3.Function call

  • The function call is a request to execute the function defined , till then function will not execute
  • No return-type should be specified at the function call
  • A user can call function any number of time and anywhere

Example :

  
int add(2,3);//invalid
add(2,3);//valid
  
4.Formal Parameters

  • The parameters present in the function definition are formal parameters
  • Formal parameters will receive value from the actual parameter
  • Formal parameters must be variable type only

Example :

  
int sum(int x,int y)//func_defination
{
return x+y;
// x and y are formal parameters
}
  
5.Actual parameters

  • Parameters passed during function call are called formal parameters
  • Actual parameters make a communication to formal parameters
  • They can be the variable, constant or expression type

Example :

  
add(2,3);//constant type actual parametres
add(x,y);//variable type actual parametres
add(2*3,7-2);//expression type actual parametres
  
6.Return statement

  • Return type specifies the function output and allocates some space to function
  • Return type also depends on arguments type

Example :

  
int sum(int,int);
float sum(int,float);
long fact(int);
  

  • Generally, it is used at the function definition end, because it makes to exit the function module
  • Another major purpose of the return statement, it exits from the function module and gives control back to the caller

  
#include"iostream"
using namespace std;
int demo()//fun definition
{
cout << "control acquired from main\n";
return 1;
//return0; error:multiple return types not allowed

}
main()
{
cout << "before call control under main\n";
cout << "controltranmsferreed from main to demo\n" << demo();
cout << "control return back from demo to main()\n" ;

}
  
output
  
before call control under main
controltranmsferreed from main to demo
control acquired from main
control return back from demo to main()
  

  • here function call at line demo() transfers function call to from main() to demo(), “return 1â€? transfers control back to main()
  • Only one return statement is allowed in a function definition
  • void return type function cannot use the return statement

Example :

  
void add()
{
return a+b;//error:void cannot return
}
  
7.Function call

It is the function in which a function call is made

Example :

  
main()//fun call
{
add(2,3);
}
  

here main() is calle for add() function, main is requesting add() to execute

8.Function signature

It is function name excluding return type in the function definition

Example :

  
int add(int x,int y)
{
return a+b;
//add(int x,int y) is function signature
}
  
Functions can be classified in 4 ways
No arguments passed and no return value
  
# include
using namespace std;
void prime();//func_protoytype
int main()
{
	// No argument is passed to prime()
	prime();//func_call
	return 0;
}
// Return type of function is void because value is not returned.
void prime()
{
	int num, i, flag = 0;
	cout << "Enter a positive integer enter to check: ";
	cin >> num;
	for(i = 2; i <= num/2; ++i)
	{
		if(num % i == 0)
		{
			flag = 1; 
			break;
		}
	}
	if (flag == 1)
	cout << num << " is not a prime number.";
	else
	cout << num << " is a prime number.";

}
  
output
  
Enter a positive integer enter to check: 3
3 is a prime number. 
  

  • In the above program, prime() is called from the main() with no arguments.
  • prime() takes the positive number from the user and checks whether a number is a prime number or not.
  • Since return type of prime() is void, no value is returned from the function.

No arguments passed but a return value
  
#include
using namespace std;
int prime();//func_protoytype
int main()
{
	int num, i, flag = 0;
	// No argument is passed to prime()
	num = prime();//func_call
	for (i = 2; i <= num/2; ++i)
	{
		if (num%i == 0)
	{
	flag = 1;
	break;
	}
	}
	if (flag == 1)
		cout<< num<<" is not a prime number.";
	else
		cout<< num<<" is a prime number.";
	return 0;
}
// Return type of function is int
int prime()//fun_def
{
	int n;

	printf("Enter a positive integer to check: ");
	cin >> n;

	return n;
}
  
output
  
Enter a positive integer to check: 12
12 is not a prime number. 
  

  • In the above program, prime() function is called from the main() with no arguments.prime() takes a positive integer from the user. Since return type of the function
  • is an int, it returns the inputted number from the user back to the calling main() function.
  • Then, whether the number is prime or not is checked in the main() itself and printed onto the screen.

Arguments passed but no return value
  
#include 
using namespace std;
void prime(int n);//fun_dec
int main()
{
int num;
cout << "Enter a positive integer to check: ";
cin >> num;
// Argument num is passed to the function prime()
prime(num);//func_call
return 0;
}
/* There is no return value to calling function. /*Hence, return type of function is void. */
void prime(int n)//func_def
{
int i, flag = 0;
for (i = 2; i <= n/2; ++i)
{
if (n%i == 0)
{
flag = 1;
break;
}
}
if (flag == 1)
{
cout << n << " is not a prime number.";
}
else {
cout << n << " is a prime number.";
}
}
  
output
  
Enter a positive integer to check: 7
7 is a prime number. 
  

  • In the above program, a positive number is first asked from the user which is stored in the variable num.
  • Then, num is passed to the prime() function where, whether the number is prime or not is checked and printed.
  • Since the return type of prime() is a void, no value is returned from the function.

Arguments passed and a return value.
  
#include 
using namespace std;
int prime(int n);//func_dec
int main()
{
int num, flag = 0;
cout << "Enter positive integer to check: ";
cin >> num;
// Argument num is passed to check() function
flag = prime(num);//func_call
if(flag == 1)
cout << num << " is not a prime number.";
else
cout<< num << " is a prime number.";
return 0;
}
/* This function returns integer value. */
int prime(int n)//func_def
{
int i;
for(i = 2; i <= n/2; ++i)
{
if(n % i == 0)
return 1;
}
return 0;
}
  
output
  
Enter positive integer to check: 5
5 is a prime number.
  

  • In the above program, a positive integer is asked from the user and stored in the variable num.
  • Then, num is passed to the function prime() where, whether the number is prime or not is checked.
  • Since the return type of prime() is an int, 1 or 0 is returned to the main() calling function. If the number is a prime number, 1 is returned. If not, 0 is returned.
  • Back in the main() function, the returned 1 or 0 is stored in the variable flag, and the corresponding text is printed onto the screen.

Which style of functions should be used?

  • All four programs above gives the same output and all are technically correct program.
  • There is no hard and fast rule on which method should be chosen.
  • The particular method is chosen depending upon the situation and how you want to solve a problem.

Some Rules and Advantages

  • Debugging: Debugging becomes easier as error sticks to that particular module(function)
  • Sourcecode Reusability: Once a function is called from any other module, without rewriting code again

Is main() user-defined or predefined function?

main()is a user-defined function

  • The body of the main() is defined by the user as per the requirement
  • The main() body can be customized as per the requirement at any time by the user
  • The return type of main can be changed

  
char main()
{
cout<<"size:"<< sizeof(main());
}
  
output
  
size is 1
  

main() satisfies all the criteria of user-defined function.

Function Scope
  
#include
using namespace std;
void demo()//func_def
{
int a=5;
cout<<"a:" << a << endl;//valid 'a' is with in the function
}
main()
{
cout<<"a:"<< a << endl;//[Error] 'a' was not declared in this scope

demo();//fun_call
}
  
output
  
a:3
  

  • All the variables which are declared inside the function are accessible within the function only but not outside the function
  • Hence variables must be used only at the place where declared

Infinite Loop in Function

  • This is very interesting to know that a function can cause an infinite loop
  • This happens when recursive calls occur without any bounds i.e no tets condition that stops the function call

  
void display();//prototype
main()
{

display();//call

}
void display()//function_def
{
cout<<"This will create infinite loop-3shaank";
display();//call itself 
}
  
output
  
This will create infinite loop-3shaank...infinite times
  

  • Initially, main() is calling the display() which is executed and again calls itself
  • As a result, execution is always within the function and control never returns to main(), which results in an infinite loop