Return - Type Name : // Function Body
Return - Type Name : // Function Body
A function is a building block of C++ programs that contains a set of statements which are
executed when the functions is called. It can take some input data, performs the given task,
and return some result. A function can be called from anywhere in the program and any
number of times increasing the modularity and reusability.
Function Definition
A function definition specifies the function name, what type of value it returns and what it
does. In C++, a function must be defined before it its used.
return_type name() {
// Function body
}
return_type: Type of value the function returns.
name: Name assigned to the function.
Function body: Set of statements in curly brackets { } are executed when the function
is called.
Example:
// Defining function that prints hello
void printHello(){
cout << "Hello Geeks";
}
The above function is named printHello. Only the single statement that prints “Hello
Geeks” is the part of function body. The return type of the function is void, which is used
when function does not return anything.
Function Call
Once the function is defined, we can use it anywhere in the program simply by calling it
using its name with () parenthesis.
Example:
{...}
// Calling function fun
printHello();
{...}
Output
Hello Geeks
The function printHello is called using its name in the main along with parenthesis. When
called, printHello’s body is executed and the text “Hello Geeks” is printed.
Return Type
We have seen an example of function that does not return anything. But functions can
return some value as a result of its execution. The type of this value should be defined as
the return_type of the function.
Example:
{...}
// Defining function that returns 10
int getTen(){
int res = 10
return res;
}
int main() {
{...}
Output
10
In this example, the getTen() function is supposed to return the integer value. So, the return
type of the function is specified as int. Then the return keyword is used to return the
variable res from the function to the point where it is called. The call of the function is
replaced by the value it returns, so res, whose value is 10 is printed.
Note: Only one value can be returned from the function, and it must be of the same type as
of function’s return type.
Parameters or Arguments
A function can also take some input data to process. These values are called function
arguments and are supplied to the function at the function call. To receive these values, we
define placeholder variables called parameter inside parenthesis in function definition. They
should be specified with their types and names.
return_type name(type1 name1, type2 name2...) {
// Function body
return val;
}
name1, name2 and so on are the parameter names using which they will be accessed in
the function.
Example:
{...}
// Defining function that prints given number
void printNum(int n){
cout << n << endl;
}
int main() {
int num1 = 10;
int num2 = 99;
{...}
Output
10
99
In the above program, printNum() function is defined with one integer parameter n that it
prints. It means that it will take one value of integer type while calling and print it. We
called printNum() two times, one with num1 and one with num2, and in each call, it prints
the given number. Note that we refer to the passed argument using the
name n not num1 or num2 in the function. It is due to the concept called scope of
variables in the main and printNum() function.
Here, there can be one question. Why didn’t we call the function with both numbers at
once? The answer lies in the printNum() definition. We have defined the function that only
takes one value of integer type as parameter, so we cannot pass two values. In other
words,
A function can only take as many arguments as specified in the function definition
and it is compulsory to pass them while calling it. Also, they should be of same type
as in the function definition.
There are also other different ways to pass arguments to the function in C++. Refer to this
article to know more – Parameter Passing Techniques in C++
Forward Declaration
In C++, a function must be defined before its call. Otherwise, compiler will throw an error.
To resolve this, we can just declare the function before the call and definition to inform the
compiler about function’s name and return type. This is called forward declaration or
just function declarations.
return_type name();
Above is the function declaration that tells the compiler that there is a function with the given
name and return type in the program. Writing parameter in the function declaration is
optional but valid.
return_type name(type1, type2 ...);
The above variation of the function declaration is also called function
prototype or function signature. If this declaration is present before the function call, then
we have the freedom to define the function anywhere in the program.
Note: Function declarations are compulsory, but the function definition already contains the
function declaration as a part of it, so it is not explicitly needed when function is defined at
the start.
Library Functions
Until now, we have discussed function which we define by ourselves. These functions are
called user defined functions for obvious reasons.
C++ also provides some in-build functions that are already defined inside different libraries
to simplify some commonly performed tasks. These functions are Library Functions which
can be directly called to perform the task.
Example:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n = 3;
int m = 6;
{...}
Output
6
The max() function in the above code returns the larger value among two values passed as
argument. It is defined in the algorithm library, so we had to include the relevant header
file <algorithm> to use it.
Similarly, C++ provides a lot of in-built functions to make our life easier. It is preferred to use
in-built functions wherever we can.
Default Arguments
Earlier, we said that it is compulsory to pass all the arguments in the function call. But C++
also provides a work around for this. For each function argument, a default value can be
defined that will be used when no value is passed for that argument in the function call.
These are called default arguments in C++.
Main Function
As you may have noticed from the above program, main is also the function. In C++,
the main function is a special function that every C++ program must contain. It serves as
the entry point for the program. The computer will start running the code from the beginning
of the main function. The return value of the main function indicates the successful or
unsuccessful execution of the program.
Recursion
When function is called within the same function, it is known as recursion. The function
which calls itself is known as recursive function and such calls are called recursive calls.
Recursion is an important concept in programming that simplifies a lot of problems are
complex to handle using normal programming means.
Function Overloading
Up until now, we know that an identifier can only be used only once in the program. The
name of the function is also an identifier, so it should be unique as well.
Image a scenario where you have a function that performs the multiplication of two integers,
but you also need to a function that multiplies two integers that are in the form of strings.
Normally, you may have to use two functions with different names for this purpose. In large
codebase, there can be many such cases and creating and remembering the names of
these functions can be hectic.
This problem can be solved though function overloading. Function overloading refers to
the feature in C++ where two or more functions can have the same name but different
parameters. It allows us to use the same function name for different arguments but same
purpose. This helps in clean semantically understandable code.
When you do not want to change the actual parameters of the function.
When you want to make copies of the data instead of the actual data.
When space is not an issue.
Usually, when you do not deal with recursion or backtracking.
#include <iostream>
using namespace std;
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
int main() {
int a = 40;
int b = 50;
cout << "Before swap: a = " << a << " b = " << b << endl;
swap(a, b);
cout << "After swap: a = " << a << " b = " << b << endl;
return 0;
}
The above program in C++ Compiler swaps the values of the variables, a and b. In
the main() function, the function call passes the actual parameter values i.e.
values of a and b to the swap() function. The swap() function swaps the values
of a and b.
Due to the call by value method, the value of the original
variables a and b remains unchanged even after swapping by the swap() function.
Output Before swap: a = 40 b = 50 After swap: a = 40 b = 50
This method does not change the original variable. In other words, it is
preserving data.
Whenever a function is called, it does not ever impact the actual contents of the
actual arguments.
Here, the value of actual arguments passes to the formal arguments. Therefore,
any changes made in the formal argument do not impact the real cases.
When a programmer opts for the call by reference, the memory space for
the formal parameters and the actual parameters are the same. All the
operations in the function are performed on the value stored at the address of
the actual parameters, and the modified value gets stored at the same address.
This technique not only conserves memory but also simplifies collaboration, as
complex data types like arrays or structures can easily be manipulated without
being duplicated needlessly.
When the programmer wants to modify the original value of a variable within a
function and have those modifications reflected in the calling code.
Suppose, you have a large object (e.g., a complex data structure or a class
instance) and you want to avoid the overhead of copying it.
When you need to modify the function parameters themselves, rather than just
the values they represent.
when working with large data, since passing by reference does not create a copy
of the data. It increases efficiency.
Call by Reference in C++ Compiler With Example
#include <iostream>
using namespace std;
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5;
int y = 10;
cout << "Before swap: x = " << x << " , y = " << y << endl;
swap(&x, &y);
cout << "After swap: x = " << x << ", y = " << y << endl;
return 0;
}
In the above program of swapping two numbers, the main()function passes
the address of the two variables, a and b as actual parameters in the function
call denoted by the reference operator &.
The swap() function uses the pointer to get the value of the variables whose
addresses are passed by the function call. After swapping the values, the value of
the actual parameters gets permanently modified as the address of the variables
is passed.
Output
The function can change the value of the argument. Thus, it is very beneficial.
It does not create duplicate data for holding values which helps in saving the
memory space.
It helps in avoiding changes that occur by mistake.
A person who reads the code is not aware that the value can be modified in the
function.
A function taking in a reference requires ensuring that the input is non-null. Thus,
a null check is not supposed to be made. Thus, it has a non-null guarantee.
Passing by reference makes the function not pure theoretically
With references, a lifetime guarantee is a big problem. It is particularly dangerous
when working with lambdas and multi-threaded programs.
Summary
<html>
<head> <style>
/* Parent selector */ body {
background-color: yellow; color: black;
} /* Child selector */
h2 { background-color: green;
color: white; }
</style> </head>
<body>
<h2>GeeksForGeeks</h2> </body>
</html>