Function in c++

function in c plus plus

In this article we will learn about function in c++ and how it works with the example.

A function is a group of statements that together perform a task. Every C++ program has at least one function, which is main() function.

To perform any task, we can create function. A function can be called many times.

Advantage of functions in C

There are many advantages of functions.

  1. Code Reusability
    -> By creating functions in C++, you can call it many times. So we don’t need to write the same code again and again.
  2. Code optimization
    -> It makes the code optimized, we don’t need to write much code.
    -> Suppose, you have to check 3 numbers (531, 883, and 781) whether it is a prime number or not. Without using the function, you need to write the prime number logic 3 times. So, there is the repetition of code.
    -> But if you use functions, you need to write the logic only once and you can reuse it several times.

Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C++ header files such as ceil(x), cos(x), exp(x), etc.

2. User-defined functions are the functions that are created by the C++ programmer so that he/she can use them many times. It reduces the complexity of a big program and optimizes the code.

Declaration of a function

The syntax of creating function in C++ language is given below:

return_type function_name(data_type parameter...)  
{    
//code to be executed    
}  

C++ Function Example

Let’s see the simple example of C++ function.

#include <iostream>  
using namespace std;  
void func() {    
   static int i=0; //static variable    
   int j=0; //local variable    
   i++;    
   j++;    
   cout<<"i=" << i<<" and j=" <<j<<endl;    
}    
int main()  
{  
 func();    
 func();    
 func();    
}  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

C++ Another Function Example

#include <iostream>
using namespace std;
 
// function declaration
int max(int num1, int num2);
 
int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;
   int ret;
 
   // calling a function to get max value.
   ret = max(a, b);
   cout << "Max value is : " << ret << endl;
 
   return 0;
}
 
// function returning the max between two numbers
int max(int num1, int num2) {
   // local variable declaration
   int result;
 
   if (num1 > num2)
      result = num1;
   else
      result = num2;
 
   return result; 
}

Output :

Max value is : 200
0 0 vote
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x