C++ Functions

In this tutorial, we will learn about the functions and how to use functions in C++ with the help of examples.


The function in C++ language is a group of statements that are created to achieve some specific task. Till now whenever we were writing main() in our code, we were calling actually the main function. This is the function every C++ program must have and the execution of any C++ program begins from the main() function.

Like the main() function, we can create any other function to complete any specific task or repetitive in nature.

Functions are declared mostly for the below reasons in any program:

  • It helps to reduce code redundancy. If a similar piece of code is being used more than once in a code, then instead of typing more than once, you can call a function in those places.
  • Editing the code in the function will change and affect all occurrences instead of writing it more than once and having to make changes in all of them.
  • It makes the code more modular and decreases the size of the total code. The code becomes easier to read and reuse the code.
  • It provides for abstraction in code. We can also use library functions without knowing the full extent of the working of a function.

Types of Functions

In C++, functions can be categories into two types. They are as follows:

  1. Library Functions: These types of functions are already defined in the C++ header file. You can use these functions without knowing much details about these functions in your program. For example: floor(x), ceil(x), exp(x), etc.
  2. User-defined Functions: These types of functions are created by C++ programmers to make their programs more optimized and less complex. They can create and use the functions as many times as they want.

In this tutorial, we will focus mostly on User-defined functions.


Function Declaration

The syntax for creating functions in the C++ programming language is as follows.

return_type function_name ( arg1_type arg1_name, ... )
{
     // body of the function
}

Here,

  • return_type – The return types of the function define the types the value a function returns. Some function after performing the desired task does not return any value. In this case, the return type of the function is void.
  • function_name – The name of the function you want to keep.
  • arg1_type arg1_name – Optional. If you want to pass any parameter to the function, you need to mention it here along with the type of the parameter.
  • body of the function – Here all the statements are written to perform the specific task.

C++ Function Example

Let’s check a simple example of a C++ function.

#include <iostream>
using namespace std;

int min(int x, int y)   // User-defined function
{ 
    if (x < y) 
    return x; 
    else
    return y; 
}   

int main()   //Code execution always begins at the main method
{
    int a = 25, b = 35; 
    // Calling above function to find max of 'a' and 'b' 
    int m = min(a, b); 

    cout << "Minimum is: " << m; 
    return 0; 
}

Output

Minimum is: 25

Calling a Function in C++

In the function definition, you will define what a function will do. Until and unless you call or invoke that function the function will not do anything.

A function is called by just writing the name of the function and passing the arguments inside it if any. Once the function is called, the control of the program is transferred to the called function. The called function performs the defined task and returns the control back to the main() function when the return statement is encountered inside the function or closing brace is reached.

If the function returns any value, you can store it. For example –

#include <iostream>
using namespace std;

// function declaration
int min(int a, int b);

int main () {
   // local variable declaration:
   int x = 50;
   int y = 100;
   int m;

   // calling a function to get max value.
   m = min(x, y);
   cout << "Min value is : " << m << endl;

   return 0;
}

// function returning the max between two numbers
int min(int a, int b) {
   // local variable declaration
   int result;

   if (a > b)
      result = b;
   else
      result = a;

   return result; 
}

Output

Min value is : 50

Function Parameters

We have seen before that a function can accept parameters and perform tasks based on the parameter value passed to them.

The parameter passed to the function is called the actual parameter. For example, in the above program 50 and 100 passed from the main() function are the actual parameters.

The parameters declared by the function to receive the values of the argument are called formal parameters. For example, in the above program, a and b are the formal parameters.

There are two popular ways to pass the parameter to the function.

  1. Call by Value – This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
  2. Call by Reference – This method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

Important points to remember for functions

For C++ programs, you need to remember the following points :

  • C++ code execution always begins at the main() function.
  • All functions have a return type and if any function does not return a value, then the return type is void. For void return type functions, you can still write only return; and it will work fine but it is optional and not giving any return statement also works perfectly fine.
  • You can return any type except for an array or function which can be done by returning a pointer to an array or function.
  • The parameter list can be either filled with parameters or be empty.
  • The function needs to be defined before the function call or needs to be declared and then can be defined elsewhere in the program.

Inline Functions

When you call a function there are many overheads like stack calls and memory allocation which can be avoided using the keyword “inline” which allows the user to define inline functions. These functions are different from other functions in the sense that the compiler replaces the code inside the inline functions instead of creating a stack and calling the function with a lengthy process. Simple and one-line codes are generally declared as inline to improve performance and reduce execution time. The following code demonstrates how to use an inline function:

#include <iostream>
using namespace std;

inline int sum(int x, int y)  // Formal Parameters
{ 
    return x+y; 
}   

int main()            
{
    int a = 100, b = 200;  
    // Calling above function to find the sum of 'a' and 'b' 
    int s = sum(a, b);   // Actual Parameters  

    cout << "Sum is: " << s;
    return 0; 
}

Output

Sum is: 300

Please get connected & share!

Categories

Advertisement