Skip to main content

C++ function

Function is binding group of statements and instruction that are executed those instruction when calling of function. Function are perform specific task. Most of programming language are providing the inbuilt function in predefined header files and library. We can used those functions. And we can also create user defined functions. Function is also called subroutine, method, procedure or routine of other programming language.

Declaration of function

prototype of function is called function declaration. Normally this are provide the behaviour of program like how many number of argument (parameter) are accepted by function. And which type of value are return by function. see the syntax

return_type function_name(Parameter_lists);
Key Points Overview
return_type Return type of a function are indicate which type are value are return by function. This value will be predefined and user defined.
function_name Name of function
Parameter_lists list of data type. If function are accept any parameters
Scope Normal function are access globally. And function of class are restricted to access only it object and inherit class object.
for examples
//Function prototype
void information();
int add(int,int);
float salary(int);

View description of those function.

/*
Function : information
Return type : void
Arguments :none (void)
Description: Function information not accept any arguments
And not return any value
*/
void information();
/*
Function : add
Return type : int (integer)
Arguments : 2 integer
Description: return addition of two integers
*/
int add(int,int);
/*
Function : salary
Return type : float value
Arguments : 1 integer (id of employee)
Description:return float value
*/
float salary(int);

observed that here not given body of function. Only given essential information. Normally most of c++ compiler are support to declared and defined function into one place.

How to use function

Basically there are three steps declare, define, and function call. In previous example there is declaring of three function. this process is declaration of function. This are not compulsory for all compiler. We can declare and defined function into single statement. See view an example.

//function example
#include<iostream>
using namespace std;
void information(){
  //body of function information
  cout<<"information function call"<<endl;
}
int add(int num1,int num2){
  cout<<"add Function call"<<endl;
  //logic code here
  //Sum of two integers
  return num1+num2;
}
float salary(int id){
  cout<<"salary Function call"<<endl;
  //code here
  int day=21;//working day
  float pay=day*3000;
  return pay;
}
int main(){
  //calling of function
  information();//execute information function
  float amount=salary(1);
  int sum=add(3,5);
  cout<<"Sum :"<<sum<<endl;
  cout<<"Amount :"<<amount;
  return 0;
}
Output
information function call
salary Function call
add Function call
Sum :8
Amount :63000

understand the behaviour of function. normally user defined function are declare at top section of after the header file.

//(for gcc compiler)
#include<iostream>
using namespace std;
void foo(){
  bar();//call another function
  cout<<"foo function"<<endl;
}
void bar(){
  cout<<"bar function"<<endl;
}
int main(){
  foo(); //calling of foo function
  return 0;
}
Compilation Error
 error: 'bar' was not declared in this scope
  bar();//call another function

so avoid this situation try to provide function prototype. see another example

#include<iostream>
using namespace std;
//function prototype
void foo();
void bar();

void foo(){
  bar();//call another function
  cout<<"foo function"<<endl;
}
void bar(){
  cout<<"bar function"<<endl;
}
int main(){
  foo(); //calling of foo function
  return 0;
}
Output
bar function
foo function

Function Calling

Function calling means execute function. This is final step and most important because this process is provide reusability. Calling of function by its name. But if function is accept any parameter then need to provide those values. This value is called parameter (arguments) of function. View an example.

//function calling example
#include<iostream>
using namespace std;
//function declaration
void display(int);

//function defination
void display(int data){
  //print value of its parameter
  cout<<"data is :"<<data<<endl;
}
int main(){
//calling of function
  display(11);
  display(2);
  display(33);
  return 0;
}
Output
data is :11
data is :2
data is :33

Note that in this program display function are executed three time. This process are provide reusability of code. main is also an function. But this are starting of program execution so this will execute by default.

We can Calling of user defined function within the function and inside of another function. But there are not possible to call outside of function. view example.

#include<iostream>
using namespace std;
//function declaration
void display(int);

//function defination
void display(int data){
  //print value of its parameter
  cout<<"data is :"<<data<<endl;
}
//calling of function globally
display(11);
display(2);
display(33);
  
int main(){
  cout<<"main function";
  return 0;
}
Output
error: expected constructor, destructor, or type conversion before '(' token
 display(11);
        ^
error: expected constructor, destructor, or type conversion before '(' token
 display(2);
        ^
error: expected constructor, destructor, or type conversion before '(' token
 display(33);
        ^

Type of function

Function are two type. predefined and user defined. predefined are exist in header file. And user defined function are defined by the programmers. Both are important role. Bases of behaviour function are 4 type.

1) No argument and no return value

This is normal case of function. Not accept value and also not return any value. See the example.

void display(void){
//code here
}
//or
void settings(){
  //code
}

2) No argument but return value

In this case function are not accept any parameter value but return value to previous function. For example.

int add(){
  int no1=1,no2=2;
  return no1+no2;
} 

3) Accepted argument but no return value

In this case function are accept any number of parameters (arguments) but not return any value. For example.

void sub(int no1,int no2){
  //code
}

4) Accepted argument and return value

In this case function are accept any number of parameter and return a value.

int sum(int no1,int no2){
  result=no1+no2;
  return result;
}

C++ function can return only one reference (address) and one value. But there are cannot return more than one value. This return value are used to display results and also used to in another statement.

Call by value & call by reference

Function are return only one value. If we are need more than one value. Then we can use of (call by reference) technique in our program.

Call by reference

This is special process. passing the address of variable in function parameter (not in value). This reference variable are utilized those value and change the value of those variable. See an example.

//C++ program to swap two integer value
#include<iostream>
using namespace std;
/*
function : swap
parameter: Accept two integer variable address
return :none
*/
void swap(int *v1,int *v2){
  //Replace value
  int temp=*v1;
  *v1=*v2;
  *v2=temp;
}

int main(){
  //local integers variable no1 no2
  int no1=20,no2=30;
  cout<<"Before no1 :"<<no1<<" no2 :"<<no2<<endl;
  swap(&no1,&no2);//pass address of variable
  cout<<"After  no1 :"<<no1<<" no2 :"<<no2<<endl;
  return 0;
}
Output
Before no1 :20 no2 :30
After  no1 :30 no2 :20

Observe that in this program swap function are not returning any value.

C++ Call By Reference Example

But this are change the value of main function variable( no1,no2). in this program passing the address of no1 and no2 variable of swap function and changed its value.

Call by value

In this process passing the value of function. This value is called actual parameter. And accepted those parameter by function that is called formal parameter. Formal parameter are change within the function. Those change not effect on actual parameter. See an example.

#include<iostream>
using namespace std;
/*
function : swap
parameter: Accept two integer value
return :none
//Formal parameter no1 no2
*/
void swap(int no1,int no2){
  //Replace value locally
  int temp=no1;
  no1=no2;
  no2=temp;
  cout<<"swap function no1 :"<<no1<<" no2 :"<<no2<<endl; 
 }

int main(){
  //local integers variable no1 no2
  int no1=20,no2=30;
  cout<<"Before no1 :"<<no1<<" no2 :"<<no2<<endl;
  //Actual parameter
  swap(no1,no2);//pass value of variable
  cout<<"After  no1 :"<<no1<<" no2 :"<<no2<<endl;
  return 0;
}
Output
Before no1 :20 no2 :30
swap function no1 :30 no2 :20
After  no1 :20 no2 :30

Note that in given program both swap and main function are local variables name is same (no1,no2).

C++ Call By Value Example

When main function is call to swap function and passing the no 1, and no2 then this value are assigned to associative function parameter of swap function. And modified the value of swap function variable. They not effect to main() function variables.

Advantage of function

question is arising in your mind why use function. Various reason to use function in c++ programming. let discussed one by one.

Code optimization

Suppose we are together make a system application. In this case there are need to perform various task. Each task are related to another one. So we can divide to those task in a sub modules and function. Because function is provide reusability then we can make function and we can use those function of many time. this process are optimize our code.

Easy to read and update

Function is divide complex task into separate sub task. This the reason code are easily to readable and modification are also easier.

Fast development

Function are provide reusability of code. That means this are increase faster development process. Define function one time and access this function in multiple time when we need.

Memory management

Executes any function of c++ program. Then stack area are allocated the memory of those executed function. This memory are used to content information like that to storing of local variables of function and function calling sequence. And after execution of program this memory are allocated for another function. This are internally process and automatically memory management. Function are provide important role to use stack memory.

Recursion

Recursion is a programming technique are used to solve programming problem. This is an contiguous function calling process to achieve desired output of a program. This is reliable to solve most of data structure problem in very easier and efficient manner. For example calculate factorial of given integer number.

//c++ program of calculate factorial 
#include<iostream>
using namespace std;
/*
function : factorial
parameter : one integer
*/
int factorial(int n){
  if(n==0){
    //base condition to stop recursion
    return 1;
  }
  //recursive calling of function by itself
  return n*factorial(n-1);
}
int main(){
  //call function
  int result=factorial(5);
  cout<<result;
}
Output
120

Recursion are very useful technique but note that most important giving a proper valid condition to stop the flow of recursion. this condition is called base and terminating condition.

C++ Factorial Recursion example

Note that in this program factorial function are executed 6 type. and main function, result variable are wait to returning value by factorial function.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment