AppDividend
Latest Code Tutorials

C++ Functions Tutorial With Example | What is Functions in C++

0

C++ Functions Tutorial With Example | What is Functions in C++ is today’s topic. A function is a group a statement which performs a specific task.  Good thing about the functions are that they are famous with many names. Different programming languages name them differently, for example, functions, methods, sub-routines, procedures, etc. If you come across any such terminology, then imagine the same concept.

What is Function in Programming Language

A function is the block of organized, reusable code that can be used to perform the single, related action.

Functions provide better modularity for our application and a high degree of code reusability. You have already seen various functions like printf() and main().

C++ Functions Tutorial With Example

There is always a default function in C++, that is main(). Besides, there are two types of functions in c++, they are

  1. Built-in function
  2. User-defined function

Why do we need functions?

Suppose in a program there is a task which is performed at several places. So, with different values, we are delivering the same task. This makes our code look lengthy and naïve. Functions come to the rescue where we can define the task to be performed at one place and pass parameters as required and get a similar result. Functions make our code modular and more professional.

Built-in function

Built-in functions are already defined in our gcc compiler, and we need to call it with the required parameter. For example: under <string.h> we have many functions, like

strlen(string_name): It returns an integer with the length of the string.

Also, there are many built-in functions like, max(), min(), pow(), sqrt() etc.

Library Function

See the following example of the Library function.

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double number1, number2;
    int op;
    cout << "Enter a number 1: ";
    cin >> number1;
    cout << "Enter a number 2: ";
    cin >> number2;
    op = pow(number1, number2);
    cout << "The output is: " << op;
    return 0;
}

See the below output.

C++ Functions Tutorial With Example

In the example above, pow() library function is invoked to calculate the power of a number.

Notice code #include <cmath> in the above program. Here, cmath is a header file. The function definition of pow()(body of that function) is present in the cmath header file.

You can use all functions defined in the cmath library when you include the content of file cmath in this program using #include <cmath> code.

Every valid C++ program has at least one function, that is, main() function.

Now, below, we will discuss the user-defined function.

A user-defined function is the function which is defined by the program according to his need. The rule, parameter everything is written by him.

Format of function in C++:

 <return_type>   Function_Name(Parameter 1, Parameter 2,…, Parameter N) {   
        // Function body                            
       // do stuff with parameters
   }

The <return_type>  can be int, float, double, long, long, long int, long double, void, string, and various possible data types.

Function_name follows the same naming convention like it should start with ‘_’ or alphabet followed by number, alphabet or ‘_.’

Parameters can be like int x, float y, string z, etc.  

An example function that calculates the area of the rectangle.

#include <iostream>  
using namespace std;  
  
float areaOfRectangle( float length, float breadth)  
{  
          // Function body  
          float calculatedArea = length*breadth;  
          return calculatedArea;  
}  
int main()  
{  
    // Sample program to show function in C++  
    // Suppose we have to calculate the area of a rectangle at several places so instead we make a function.  
  
    float length, breadth;  
    cout << "Enter length and breadth :\n";  
    cin >> length >> breadth;  
    float answer = areaOfRectangle(length,breadth); // Pass the parameters  
    // store the result in answer  
    cout << "Area : " << answer << "\n";  
    return 0;  
}  

Calling a function is not such a big deal. One has to pass the parameters and call the function by Function_name. It can be seen in the above code where the function areaOfRectangle is called with parameters length and breadth.

How To Declare Function in C++

If the user-defined function is defined after main() function, the compiler will show the error. It is because the compiler is unaware of user-defined function, types of an argument passed to a function and return type.

In C++ language, function prototype is the declaration of function without its body to give compiler information about the user-defined function. Function prototype in the above example is the following.

int add(int, int);

You can see that, and there is nobody of function in the prototype. Also, there are only return the type of arguments but no arguments. You can also declare function prototype as below, but it’s not necessary to write arguments.

int add(int a, int b);

How To Call Function in C++

If we want to execute the codes of the function body, a user-defined function needs to be invoked(called).

In the above program, add(a, b) inside the main() function calls the user-defined function.

The function returns an integer which is stored in the variable.

How To Pass Arguments of Functions in C++

In the programming language, argument (parameter) refers to a data which is passed to the function (function definition) while calling it.

In the below example, two variables,  x, and y are passed to function during the function call. These arguments are known as actual arguments.

The value of a and b are initialized, respectively. These arguments a and b are called formal arguments.

Inside the main function, we call the multiply() function in which we pass the actual parameters x and y.

So, in the below code int a, int b are formal parameters and int x, int y are actual parameters.

 See the following code.

#include <iostream>
#include <cmath>

using namespace std;

int multiply(int a, int b)
{
    int c;
    c = a * b;
    return c;
}
int main()
{
    int x = 19, y = 21, result;
    result = multiply(x, y);
    cout << result;
}

Talking about parameters, parameters can be passed in two ways, namely:

  1. Call by Value
  2. Call by reference

Using Call by Value

In this method, just the values of the parameters assigned are passed so, any changes made to the parameters passed inside the function body will not change its value in the main function.

#include <iostream>  
using namespace std;  
  
int dostuff( int x, int y)  
{  
          // Function body  
          x = x+y; // change made here will not be reflected in main.  
          return x;  
}  
int main()  
{  
    // Sample program to show call by value.  
    int x,y;  
    cin >> x >> y;  
    int answer = dostuff(x,y); // Pass the parameters  
    // Value of x will not be changed here.  
    cout << x;  
  
    return 0;  
}  

In the code above, x and y have been passed by value to dostuff. In the function dostuff, x has been changed to x+y, but this change is not reflected in the main function.

call by value example

Using Call by Reference

In this method, parameters passed into the function are referenced with arguments of the function using the operator ‘&’.  Changes made to reference variable inside the body function will be reflected inside the main function.

#include <iostream>  
using namespace std;  
  
int dostuff( int &x, int y)  
{  
          // Function body  
          // Look for '&' before x in int &x above.  
          x = x+y; // change made here will be reflected in main.  
          return x;  
}  
int main()  
{  
    // Sample program to show call by reference.  
    int x,y;  
    cin >> x >> y;  
    int answer = dostuff(x,y); // Pass the parameters  
    // Value of x will be changed to x+y here.  
    cout << x;  
  
    return 0;  
}  

Above code tells about the call by reference type passing of parameters. The x parameter has been passed as a reference variable. Inside the argument of function dostuff, int &x  is used instead of int x. Changes made to x, i.e. x=x+y is reflected in the main function.

call by reference example

Can we pass fewer parameters than defined in function definition?

Yeah. This can be done using default parameters. Default parameters should be present only at the end of the arguments. Below example will explain the concept.

#include <iostream>  
using namespace std;  
  
int multiply( int x, int y,int z=1)  
{  
          // Function body  
          // If only two inputs are there then z will be 1.  
          return x*y*z;  
}  
int main()  
{  
    // Sample program to show default parameters.  
    int x,y,z;  
    x=4; y=10; z=3;  
    // Multiplication of 3 numbers  
    cout << multiply(x,y,z) << "\n";  
    // Multiplication of 2 numbers same function can be used  
    cout << multiply(x,y) << "\n";  
  
    return 0;  
}  

Here the multiply function can be used for both 3 numbers and 2 numbers. z has been set by default to 1. Notice that it has been placed at the end in the arguments. In case only two arguments are passed, it will set the value of z=1.

Finally, C++ Functions Tutorial With Example | What is Functions in C++ is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.