The Power of Functions in C++

Welcome to the 8th Tutorial on C++ Tutorials for beginners series. This is the first tutorial on C++ functions, a very important aspect of any programming language. Functions are often called methods as well in some programming languages, but in this tutorial we will restrict ourselves to the word function.

In this tutorial we will jump into the very basics of functions. We will describe what a function is, what its uses are, and then will give a few examples of how a function can be used in C++.

In the end we will see how functions can receive arguments and will explain this argument passing with the help of passing an array and string to this function with the help of pointers. So stay with us, you are going to learn something really awesome which will make your code a lot more organized and readable.

As custom of this series, we will start with an empty console application.

#include <iostream>
using namespace std; 

int main()
{
    //code here

    return 0;
}

Contents:

  • 1. Uses of functions in C++
  • 2. Use of return statement in function
  • 3. Passing Arguments to function
  • 4. Passing Array as function argument using pointer
  • 5. Passing Strings as function argument using pointers
  • 6. Project (Calculator Using Functions)

1- Uses of functions in C++

Functions are set of statements which collectively perform some function and may or may not return some value. This seems a bit tricky but we will explain this in detail. Functions modularize your code and can save you writing the same code again and again. Whenever you come across a piece of code which is repetitive, you can write that code inside the body of function and call that function whenever you want to execute that piece of code. This organizes the code and also promotes re-usability along with proper structuring of code. If you look at C++ code, it always contains at least once function the main() function.

So, how do you declare a function? Let’s look at the syntax of a function:

void func1()
{
    // body of the function
}

This is the simplest example of a function. Let’s break it down to explain what is happening in this piece of code.

void:

This is the type of value, a function returns, it can be int, double, float or any data type. It can also return custom objects. In this case void means that this function will return no value. Remember you will have to return a value if you choose not to use void, otherwise it may result into compiler error.

func1():

This is the name of the function, a function is called by its name followed by parenthesis. Inside the parenthesis, arguments are passed which we will discuss later. In this case no arguments are being passed.

Now we will write a simple program which will elaborate the concepts we have just discussed. Note that in C++ we will need to declare the prototype functions before the main function. Then the functions below main will work without the compiler calling an error.

Example1:

#include <iostream>
using namespace std;

// necessary prototypes of the functions in c++
int fun1();
void fun2();

int main()
{
    int num1 = 10;

    cout << num1 + fun1();

    fun2();
}

int fun1()
{
    return 10;
}

void fun2()
{
    cout << "\nThis function returns nothing";
}

In this program we are using two functions; the first one is named fun1.

fun1” simply returns a hard coded value which is 10 in this case. When this function is called in the main function it will return 10 which will be added to int type variable num1 which also contains value 10 in the main function and the result will be displayed which will be 20.

Note, whenever you call a function you don’t mention its return type, you just have to name it followed by parenthesis and pass any arguments if required.

Example:

int main()
{
    fun2(); //call function
}

The return type of “fun2” is of type void which means that this function will not return anything; it will simply execute the code inside the function. The following is the output from example 1.

Output 1:

2- Use of “return” in Functions

The return statement has two major uses inside a function:

1. It terminates a function and the control is shifted to the calling function where execution continues after the function call. If return is used inside the main function, it will return control to operating system.

2. The return statement can be used to return values from a function as seen in example 1 where fun1 returned integer value of 20.

3- Passing Arguments to a Function

Arguments can also be passed to functions. Passing arguments to functions has a very simple syntax in C++. Take a look at the following line of code below:

int fun1(int a, int b)
{
    //code here
}

This function accepts two arguments of type int. As mentioned in the parenthesis. The name ‘a’ and ‘b’ is just a way to present the arguments. You can use any name, but then these arguments will be called by the same name inside the function body as you have mentioned in the parenthesis.

For the above function you will call it like this:

int fun1(int, int);

int main()
{
    fun1(4, 7);
}

Let’s have a look at the following example to elaborate on this concept a bit more:

Example 2:

#include <iostream>
using namespace std;

int fun1(int, int);

int main()
{
    int sum;

    sum = fun1(5, 7);

    cout << sum;
}

int fun1(int a, int b)
{
    int sum = a + b;

    return sum;
}

In the example 2, we have a function named fun1 which accepts two arguments of type int. It adds the values of those arguments and return its value. This function is called in the main function where two parameters have been passed according to the function definition. These are 5 and 7. The function will calculate sum and will return 12 which will be displayed.

Note: When calling the function, the order of the parameters passed to the function call must be in the same order as defined in the function definition. If the first argument is of type char, calling the function should pass the first argument of type char, otherwise a compiler error will occur. Here is the output of Example 2.

Output 2:

4- Passing Arrays as a function argument using Pointers

Like an ordinary data type, an array can also be passed to a function using pointer. In such case the argument type will be like a pointer variable. This pointer variable will point to the first index of the array which will be passed. We have studied this concept in tutorial 7 on pointers where in the case of pointer arrays, the pointer variable points to the first element. This concept is elaborated in the following example. Note: In example 3 we have defined the sum function before the main function, it eliminates the need for writing a prototype of the function definition before the main function.

Example 3:

int sum(int* arr, int size)
{
    int sum = 0;

    for (int i = 0; i < size; i++)
    {
        sum = sum + arr[i];
    }

    return sum;
}

int main()
{
    int result;
    int abc[] = { 18, 14, 10, 5, 13 };

    result = sum(abc, 5);

    cout << "Sum of elements of array is: " << result;
}

In example 3 we have a function named sum whose first argument int * arr which is the pointer that will point to the first index of the array passed from the main function. The second argument is the size of the array which will be passed. The sum function calculates the sum of all the elements of array abc (18, 14, 10, 5, 13) which has its address passed into the sum function pointer arr. The sum equals 60 which is the sum of all the numbers in the abc[] array in the main function. Below is what you see when you run the program.

Output 3:

5- Passing strings as function arguments using Pointers

Like arrays, strings can also be passed as function arguments using pointers. The string pointer argument will point to the starting index of a string which will contain the first character of string. This concept has already been explained in tutorial 7 on pointers. Here is the example of how a string is passed to function using pointer.

Example 4:

void display(const char* string)
{
    cout << string;
}

int main()
{
    display("Tutorialboneyard");
}

This is a very simple example where the function accepts the pointer const char of type string and displays that string. In the main function we call the display function and pass it a string value in quotations which is “Tutorialboneyard” in this case. The display function prints this value. Here is the output of this code.

Output 4:

6- Project (Calculator Using Functions)

Remember we programmed a calculator in 5th tutorial on switch and loop statements. Here we are going to program a similar calculator using functions. We will write four functions, one each for addition, subtraction, multiplication and division and will call these functions to perform arithmetic instead of performing calculations as we did in this tutorial on C++ functions. At the end of this project, you will understand how functions help in re-usability and modularity of code. Here is the code for this project.

Code:

// *** Basic Calculator Project using functions ***

#include <iostream>
using namespace std;
 
int add(int a, int b)
{
    return a + b;
}

int subtract(int a, int b)
{
    return a - b;
}

int multiply(int a, int b)
{
    return a * b;
}

int divide(int a, int b)
{
    return a / b;
}

int main()
{
    int num1, num2;
    double result;
    char option, cont;

    cout << "*** Basic Calculator Project ***";

    do
    {
        cout << "\nEnter the first number:";

        cin >> num1;

        cout << "Enter the 2nd number: ";

        cin >> num2;

        cout << "Enter the operation to perform(+, -, *, /):";

        cin >> option;

        switch (option)
        {
            case '+':
                {
                    result = add(num1, num2);

                    cout << "\nThe answer of Addition is:" << result;

                    break;
                }

            case '-':
                {
                    result = subtract(num1, num2);

                    cout << "The answer of subtraction is:" << result;

                    break;
                }

            case '*':
                {

                    result = multiply(num1, num2);

                    cout << "The answer of multiplication is:" << result;

                    break;
                }

            case '/':
                {

                    result = divide(num1, num2);

                    cout << "The answer of division is:" << result;

                    break;

                }
        }

        cout << "\nDo you want to perform another operation? (y/n)";

        cin >> cont;
    }

    while (cont == 'y');
}

In the above code, four functions that add, subtract, multiply and divide have been added which perform the calculations and return the results. In the main function they have been called inside the switch statement depending upon the choice of the user. The output of this code with the user selections is as follows.

Project Output:

You might also want to read:

Part 1 – Installing Visual Studio C++

Part 2 – The Basics of C++

Part 3 – Conditional “if” Statement

Part 4 – else if Statement in C++

Part 5 – “switch and loops”

Part 6 – Arrays & Strings

Part 7 – Pointers

Part 8 – Functions in C++

If you like this page please share with your friends.

Leave a Comment

Your email address will not be published. Required fields are marked *