A Function is a collection of statements designed to perform a specific task. The function is like a black box that can take specific input(s) as its parameters and output a value that is the return value. A function is created to use it as many times as needed just by using the function’s name. You don't need to type the function’s statements whenever required; you just have to call the function. A function is a block of code that only runs when called.
Every C++ program has at least one function, which is main().
Defining a function: It provides information about the function attributes such as its name, return type, parameters, and body.
Syntax to define a function:
return_type functionName(parameter1, parameter2, ...) {
// function body
}
Here,
- Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value, So in that case, the return_type is the keyword void. Some other return_type can be int, string, vector, float, etc.
- Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.
- Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as an actual parameter or argument. The parameter list refers to the type, order, and the, number of function parameters. Parameters are optional; that is, a function may contain no parameters.
- Function Body − The function body contains a collection of statements that define what the function does.
Example: In this example, we define a function that accepts two parameters and returns the maximum of two numbers.
int max(int x, int y) {
if (x > y)
return x;
else
return y;
}
Here, the return type is int, so it means it will return an integer value where the function will be called.
C++ Function Prototype
A function prototype is a declaration of the function that tells the program about the type of the value returned by the function and the number and type of arguments.
Function prototyping is one very useful feature of the C++ function. A function prototype describes the functional interface to the compiler by giving details such as the number and type of arguments and return values.
Function Declaration: When a function is defined before the main() function in the program, then function declaration is not required, but writing the function after the main() function requires function declaration first, else there will be a compilation error.
Syntax to declare a function:
return_type function_name( parameter list );
Example:
int sum(int num1,int num2);
Can be declared as
int sum(int,int)
Example:
#include <iostream>
using namespace std;
//Function declaration
int sum(int, int);
int main() {
//Calling the function
cout << sum(50, 60);
return 0;
}
/* Function is defined after main*/
int sum(int num1, int num2) {
int num3 = num1 + num2;
return num3;
}
Output:
110
Function Calling in C++: Once we declare a function, we use it to perform some specific task. When we call a function, the program controls transfer to the called function.
Syntax to call a function:
function_name( parameters );
Example:
#include<iostream>
using namespace std;
int max(int x, int y) {
if (x > y)
return x;
else
return y;
}
int main() {
int a = 10;
int b = 20;
// Method Calling
int maximum = max(a, b);
cout << maximum;
return 0;
}
Output:
20
How does function calling work?
Example:
#include <iostream>
using namespace std;
int findSum(int a, int b) {
int sum = a + b;
return sum;
}
int main() {
cout << findSum(50, 60);
return 0;
}
Output:
110
The function being called is called callee(here it is findsum function), and the function which calls the callee is called the caller (here, the main function is the caller).
When a function is called, program control goes to the function’s entry point. The entry point is where the function is defined. So focus now shifts to the callee, and the caller function goes in a paused state.
Why do we need function?
- Reusability: Once a function is defined, it can be used repeatedly. You can call the function as many times as needed, which saves work. Consider that you are required to find out the area of the circle. Now either you can apply the formula every time to get the circle area or make a function to find the circle area and invoke the function whenever needed.
- Neat code: A code created with a function is easy to read and dry run. You don’t need to repeatedly type the same statements; instead, you can invoke the function whenever needed.
- Modularisation: Functions help in modularizing code. Modularisation means divides the code into small modules, each performing a specific task. Functions allow in doing so as they are the program’s tiny fragments designed to perform the specified task.
- Easy Debugging: It is easy to find and correct the error in function compared to raw code without function where you must correct the error everywhere the specific task of the function is performed.
There are two types of function in C++ they are:
- Built-in Functions
- User-defined Functions
We will closely look at both of them in the next notes.
1. Built-in Functions: Built-in functions are also known as library functions. These functions are not required to be declared, raised, and defineed by the user, these functions are already present in the C++ libraries such as iostream, cmath, etc. Some predefined functions are: sqrt(), max(), min(), round(), etc. these are defined inside the cmath library.
Example 1: Find the maximum of two numbers using the built-in function.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
// Maximum of two numbers using max()
int maximum = max(100, 30);
cout << maximum;
return 0;
}
Output:
100
Example 2: Find the minimum of two numbers using the built-in function.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
// Minimum of two numbers using min()
int minimum = min(100, 30);
cout << minimum;
return 0;
}
Output:
30
Example 3: Find the square root of a number using the built-in function.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
// Finding sqrt using sqrt()
double root = sqrt(144);
cout << root;
return 0;
}
Output:
12
Example 4: Find string length using the built-in function.
#include <iostream>
using namespace std;
int main() {
// Finding length using length()
string a = "vedant";
cout << a.length();
return 0;
}
Output:
6
Example 5: Convert the string into the upper case using the built-in method.
#include <iostream>
#include<cctype>
using namespace std;
int main() {
// Converting to uppercase using toupper()
string a = "vedant";
for (int i = 0; i < a.length(); i++)
putchar(toupper(a[i]));
return 0;
}
Output:
VEDANT
2. User-defined Functions: The function written by the user or programmer’s function is called the user-defined method. We can modify these methods based on our requirements. Let’s discuss the user-defined functions with all four combinations of arguments and return type.
- Function with no argument and no return value
- Function with arguments but no return value
- Function with no arguments but returns a value
- Function with arguments and return value
i) Function with no argument and no return value: When a function has no arguments, it does not receive any calling function data. Similarly, when it does not return a value, the calling function does not receive any called function data.
Syntax:
Function declaration : void function();
Function call : function();
Function definition :
void function()
{
statements;
}
Example: Check whether a number is even or odd.
#include <iostream>
using namespace std;
// Function to check a number is even or odd
void checkEvenOdd() {
// Number to be checked
int num = 24;
if (num % 2 == 0)
cout << "Even Number";
else
cout << "Odd Number";
}
//Main Code
int main() {
//Function Calling
checkEvenOdd();
return 0;
}
Output:
Even Number
ii) Function with arguments but no return value: When a function has arguments, it receives data from the calling function, but it returns no values.
Syntax:
Function declaration : void function(int x);
Function call : function(x);
Function definition :
void function(int x)
{
statements;
}
Example: Check whether a number is even or odd.
#include <iostream>
using namespace std;
// Function to check a number is even or odd
void checkEvenOdd(int num) {
if (num % 2 == 0)
cout << "Even Number";
else
cout << "Odd Number";
}
//Main Code
int main() {
// Number to be checked
int num = 24;
//Function Calling
checkEvenOdd(num);
return 0;
}
Output:
Even Number
iii) Function with no arguments but returns a value: There could be occasions where we may need to design functions that may not take any arguments but returns a value to the calling function.
Syntax:
Function declaration : int function();
Function call : function();
Function definition :
int function()
{
Statements;
return x;
}
Example: Add two numbers.
#include <iostream>
using namespace std;
// Function to return the sum of two numbers
int sumOfTwoNumbers() {
int a = 10;
int b = 20;
int sum = a + b;
return sum;
}
//Main Code
int main() {
// No arguments passed in the function
int sum = sumOfTwoNumbers();
cout << sum;
}
Output:
30
iv) Function with arguments and returns a value :
Syntax:
Function declaration : int function(int x);
Function call : function(x);
Function definition :
int function(x)
{
Statements;
return x;
}
Example: Add two numbers.
#include <iostream>
using namespace std;
// Function to return the sum of two numbers
int sumOfTwoNumbers(int a, int b) {
int sum = a + b;
return sum;
}
//Main Code
int main() {
int a = 10;
int b = 20;
int sum = sumOfTwoNumbers(a, b);
cout << sum;
}
Output:
30
The parameters passed to function are called actual parameters. In the example below, a and b are actual parameters.
The parameters received by the function are called formal parameters. In the example below, x and y are formal parameters.
Example:
#include <iostream>
using namespace std;
void increment(int x, int y) { // x and y are formal parameters
x++;
y = y + 2;
cout << x << ": " << y << endl;
}
//Main Code
int main() {
int a = 10, b = 20;
increment(a, b); // a and b are actual parameters
cout << a << ": " << b;
}
Output:
11: 22
10: 20
There are two most popular ways to pass parameters, which are:
- Pass by Value
- Pass by Reference
i) Pass by Value: Here, values of actual parameters are copied to the function’s formal parameters, and the two types of parameters are stored in different memory locations. Any changes made inside functions are not reflected in the actual parameters of the caller.
Example:
#include<iostream>
using namespace std;
void func(int x) {
x = 50;
cout << "Value of x in func function: " << x << endl;
}
//Main Code
int main() {
int x = 10;
func(x);
cout << "Value of x in main function: " << x;
}
Output:
Value of x in func function: 50
Value of x in main function: 10
ii) Pass by Reference: Here, both actual and formal parameters refer to the same location, so any changes made inside the function are reflected in the actual parameters of the caller.
Example:
#include<iostream>
using namespace std;
void func(int &x) {
x = 50;
cout << "Value of x in func function: " << x << endl;
}
//Main Code
int main() {
int x = 10;
func(x);
cout << "Value of x in main function: " << x;
}
Output:
Value of x in func function: 50
Value of x in main function: 50
Function overloading is a programming feature in C++ that allows having more than one function having the same name but different parameter list, it means the data type and sequence of the parameters or the different number of parameters, for example, the parameters list of function myfuncA(int x, float y) is (int, float) which is different from the function myfuncA(float x, int y) parameter list (float, int).which is also different from myfuncA(float a) parameter list (float). Function overloading is related to compile-time polymorphism.
Example: Following are the 4 overloaded functions
int test() {}
int test(int a) {}
float test(double a) {}
int test(int a, double b) {}
Note: Functions can not be overloaded if they differ only in the return type.
Example: Here, both functions have the same name, same type, and the same number of arguments. Hence, the compiler will throw an error.
int test(int a) {}
double test(int b) {}
Ways to overload a function: There are two ways to overload a function, and they are:
- By Changing the number of arguments.
- By Changing the data type.
1. Function overloading with changing the number of arguments.
In this example, we have created two functions, the first add() performs the addition of the two numbers, and the second add() performs the addition of the three numbers. Let’s look at the example:
#include <iostream>
using namespace std;
// Function with two parameters
int add(int num1, int num2) {
return num1 + num2;
}
// Function with three parameters
int add(int num1, int num2, int num3) {
return num1 + num2 + num3;
}
int main() {
cout << add(10, 20) << endl;
cout << add(10, 20, 30);
return 0;
}
Output:
30
60
2. Function overloading with changing the data type of arguments.
In this example, we have created two add() functions with different data types. The first add() takes two integer arguments and the second add() takes two double arguments.
#include <iostream>
using namespace std;
// Function with two integer parameters
int add(int num1, int num2) {
return num1 + num2;
}
// Function with two double parameters
double add(double num1, double num2) {
return num1 + num2;
}
int main(void) {
cout << add(10, 20) << endl;
cout << add(10.4, 20.5);
return 0;
}
Output:
30
30.9
A default argument is a value provided in a function declaration automatically assigned by the compiler if the caller of the function doesn’t provide a value for the argument with a default value. However, if arguments are passed while calling the function, the default arguments are ignored.
Example: A function with default arguments can be called with 2 or 3 or 4 arguments.
#include<iostream>
using namespace std;
int add(int x, int y, int z = 0, int w = 0) {
return (x + y + z + w);
}
int main() {
cout << add(10, 20) << endl;
cout << add(10, 20, 30) << endl;
cout << add(10, 20, 30, 40) << endl;
return 0;
}
Output:
30
60
100