Functions in C++

Functions

On this page we will discuss about Functions in C++. 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.
function in c++

Functions in C++

Below is the syntax of the Functions in C++ with example

Syntax:

return_type func_name(args)//function definition
{
---
stmts;//fun_body
}

Example:

int add()//func_def
{
int a=2,b=3;//fun_body
return a+b;
}
Functions in C++

Functions in C++ are defined in 2 ways:

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);
ex:
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
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
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
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
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
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
Run
#include <iostream>
using namespace std;
int demo()//fun definition
{
cout<<"control acquired from main\n";
return 1;
//return0;error:multiple return types not allowed
}
int 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";
return 0;
}
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
void add()
{
return a+b;//error:void cannot return
}

7.Function call

It is the function in which a function call is made
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
int add(int x,int y)
{
return a+b;
//add(int x,int y) is function signature
}

Functions in C++ can be classified in 4 ways

No arguments passed and no return value

Run
#include <iostream> 
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.";

}
  • 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

Run
#include <iostream>
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;
}
  • 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

Run
#include <iostream>
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.";
}
}
  • 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.

Run
#include <iostream>
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;
}
  • 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.

Factorial Program using functions(no return type no parameter)

Run
#include <iostream>
using namespace std;
void fact();//func_declartion
main()//func_calle
{
fact();//function call
fact();//func_call
}
void fact()//func_definition
{
int n;
cout<<"enter n value:"; cin>>n;
long f=1;
while(n==1)
{
f=f*n;
n--;
}
cout<<"factorial:"<<f;
}
o/p
enter n value:5
factorial:120

Advantages of Functions

  • 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.

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
int 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

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription