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 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 easier and fascinating.

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


#include

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 bit tricky but we will explain this doesn’t worry. Function modularizes your code and can save you writing 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 can call that function whenever you want to execute that piece of code. This organizes the code and also promotes reusability along with proper structuring of code. If you look at C++ code, it always contains at least once function the main() function.

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


void func1 ()

{

	// body of the function

}

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

void:

This 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 function will return no value. Remember you will have to return the value if define in function syntax otherwise it may result into compiler error.

func1():

This is the name of the function, a function is called by its name followed by round brackets. Inside brackets, 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();

	getchar();// Just to prevent screen from disappearing

	cin.get();// Just to prevent screen from disappearing

}

int fun1()

{

	return 10;

}

void fun2()

{

	cout << "\nThis function returns nothing";

}

There is a point worth noting in this code. In C++ whatever compiler calls. It needs to know its syntax. Hence, we have to define the prototype or in simpler words syntax of the function above the main function in order to call these functions from main functions. In this program we are using two functions; first one is named function fun1.

“fun1” simply returns a hardcoded value which is 10 in this case. When this function is called in main function it will return 10 which will be added to int type variable num1which 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.

Return type of “fun2” is void which means that this function will not return anything; it will simply execute the code inside the function. Following is the output of this code.

Output1:

 

2- Use of return in functions

Return statement has two major uses inside a function:

* First one is it is used to terminate a function and the control is shifted to the calling function where execution continues after the function call. If return is used inside main function, it will return control to operating system.

* Return statement can be used to return values from a function as seen in example1 where fun1 returned integer value of 20.

 

3- Passing Arguments to a function:

Arguments can also be passed to function based on which function performs some specific task. Passing arguments to function has a very simple syntax in C++. Take a look at following line of code:

int fun1(int a, int b)

{

}

 

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.

 

When you call a function which arguments you have to pass the value of those arguments in the function call. For the above function you will call this function as:

	int fun1(4,7)

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

Example2:


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 example2, we have a function named fun1 which accepts two arguments of type int, add the values of those arguments and return its value. This function has been called in 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 has been 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 like, if the first argument is of type char, calling function should pass first argument of type char otherwise compiler error will be occurred. Here is the output of Example2.

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:


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;

}

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:


void display(char * string)

{

	cout << string;

}

int main()

{

	display("Tutorialboneyard");

}

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:

 

#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 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

 

More C++ Tutorials:

 

Share with your friends:

Leave a Reply

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