The Power of Functions in C++

Welcome to the 8th Tutorial on C++ Tutorials for beginners series. This is this is 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 basically a function is, what its uses are and then will give few examples of how a function can be used in C++.

In the end we will see how a function can be passed an argument 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.

Example1:

#include <iostream>
using namespace std;

int fun1();
void fun2();

int main()
{
    int num1 = 10;

    cout << num1 + fun1();

    fun2();
}

int fun1()
{
    return 10;
}

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

There is a point worth noting in this code. In C++ the compiler needs to know the functions call. Hence, we have to define the prototype or in simpler words, the syntax of the function in the main function in order to call these functions. 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.

Output1:

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.

Output2:

4- Passing array as 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 case of pointer array the pointer variable points to the first element. This concept is elaborated in following example.

Example3:

[code lang="cpp"]

int sum(int *arr, int size)

{

	int sum=0;

	for (int i=0; i&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; size; i++)

	{

		sum = sum + arr[i];

	}

	return sum;

}

int main()

{

	int result;

	int abc[] = {18,14,10,5,13};

	result = sum(abc, 5);

	cout&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; "Sum of elements of array is: "&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;result;

}
[/code]

Note: In the example3 we have defined the sum function before the main function, it eliminates the need for writing a prototype of function definition before the main function.

In example three we have a function named sum whose first argument int * arr is the pointer which 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 and returns the result. The sum of the elements of array is 60 as we can manually calculate hence the sum function returns 60 after performing calculations.

Output3:

5- Passing string as function argument using Pointers:

Like arrays, strings can also be passed as function arguments using pointer. The string pointer argument will point to the starting index of 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.

Example4:

[code lang="cpp"]

void display(char * string)

{

	cout &amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; string;

}

int main()

{

	display("Tutorialboneyard");

}

[/code]

This is a very simple example here the function display accepts the pointer to character type string and displays that string. In the main function we call the display function and pass it a string value which is “Tutorialboneyard” in this case. Display function displays this value. Here is the output of this code.

Output4:

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 in the main functions as we did in tutorial functions. At the end if this project, you will understand how functions help in reusability and modularity of code. Here is the code for the project.

Code:

[code lang="cpp"]
#include &amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;iostream&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
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 &amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;"*** Basic Calculator Project ***";

	do

	{

		cout&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;"\nEnter the first number:"; cin&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; num1;

		cout&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;"Enter the 2nd number: "; cin&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; num2;

		cout&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;"Enter the operation to perform(+, -, *, /):"; cin&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; option;

		switch(option)

		{

			case '+':

			{

			result = add(num1,num2);

			cout&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;"\nThe answer of Addition is:"&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;result;

			break;

			}

			case '-':

			{

			result = subtract(num1,num2);

			cout&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;"The answer of subtraction is:"&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;result;

			break;

			}

			case '*':

			{

			result = multiply(num1, num2);

			cout&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;"The answer of multiplication is:"&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;result;

			break;

			}

			case '/':

			{

			result = divide (num1, num2);

			cout&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;"The answer of division is:"&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;result;

			break;

			}

		}

		cout&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;"\nDo you want to perform another operation? (y/n)"; cin &amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt; cont;

	}

	while (cont == 'y');

}
[/code]

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

Project Output:

You might want to continue and read…

C++ for Beginners Part 7 – Pointers

C++ for beginners Part 6 – Arrays & Strings

C++ for beginners Part 5 – “switch and loops”

C++ for beginners Part 4 – else if Statement in C++

C++ for beginners Part 3 – Conditional “if” Statement

C++ for beginners Part 2 – The Basics of C++

C++ for beginners Part 1 – Installing Visual C++ Express

Share with your friends:

Leave a Comment

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